基于值从嵌套dict检索密钥,其中密钥名称未知

2024-05-15 00:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下意见:

{
  'foo': {
    'name': 'bar',
    'options': None,
    'type': 'qux'
  },
  'baz': {
    'name': 'grault',
    'options': None,
    'type': 'plugh'
  },
}

顶级键的名称在运行时未知。我无法确定如何获取顶级键的名称,其中type的值为plugh。我尝试过各种迭代器、循环、理解等,但我对Python不是很在行。任何指点都将不胜感激


Tags: name名称nonefootypebarbaz顶级
3条回答

尝试迭代dict键并检查元素

for key in d:
    if(d[key]['type'] == 'plugh'):
        print(key)
baz

您需要像这样迭代数据:

def top_level_key(search_key, data):
    for key, value in data.items():
        if value['type'] == search_key:
            return key

print(top_level_key('plugh', data_dict))

试试这个:

for key, inner_dict in dict_.items():
    if inner_dict['type'] == 'plugh':
        print(key)

或者,如果使用一行程序来获取与条件匹配的第一个密钥:

key = next(key for key, inner_dict in dict_.items() if inner_dict['type'] == 'plugh')
print(key)

输出:

baz

相关问题 更多 >

    热门问题