Python嵌套字典通过特定子键进行访问

2024-06-16 13:41:22 发布

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

我想知道以下字典中的哪个键属于特定子键:

dic = {'key1':{'subkey1':'entry1', 'name':'entry2'},
       'key2':{'subkey3':'entry3', 'name':'entry4'},
       'key3':{'subkey5':'entry5', 'name':'entry6'}}

例如:哪个键属于entry4

for i in dic.keys():
    if dic[i]['name'] == 'entry4':
        print(i)
        break

答案是:键2

有没有更简单/更好的方法


Tags: name字典key2key1key3dicentry1entry3
2条回答

正如@Samwise在评论中已经建议的那样:

[key for key, subdic in dic.items() if 'entry4' in subdic.values()] 

输出:

['key2']

注意:它返回一个列表,因为可能有多个匹配项

如果您只关心第一个匹配项,或者如果您确定没有重复项,则可以使用:

matching_keys = [key for key, subdic in dic.items() if 'entry4' in subdic.values()]
matching_keys[0]

输出:

'key2'

试试这个

dic = {'key1':{'subkey1':'entry1', 'name':'entry2'},
       'key2':{'subkey3':'entry3', 'name':'entry4'},
       'key3':{'subkey5':'entry5', 'name':'entry6'}}

print(''.join(x for x, y in dic.items() if 'entry4' in y.values()))

输出

key2

相关问题 更多 >