我有以下结论:
{
'foo': {
'name': 'bar',
'options': None,
'type': 'qux'
},
'baz': {
'name': 'grault',
'options': None,
'type': 'plugh'
},
}顶级键的名称在运行时是未知的。我不知道如何获取type的值为plugh的顶级键的名称。我尝试过各种迭代器、循环、理解等,但我对Python不是很在行。如有任何建议,我们将不胜感激。
发布于 2021-02-05 14:47:22
尝试遍历dict键并检查元素
for key in d:
if(d[key]['type'] == 'plugh'):
print(key)baz发布于 2021-02-05 14:47:09
试试这个:
for key, inner_dict in dict_.items():
if inner_dict['type'] == 'plugh':
print(key)或者,如果您使用one liner来获取匹配条件的第一个键:
key = next(key for key, inner_dict in dict_.items() if inner_dict['type'] == 'plugh')
print(key)输出:
baz发布于 2021-02-05 14:50:13
你需要像这样迭代你的数据:
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))https://stackoverflow.com/questions/66058787
复制相似问题