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

Python嵌套字典通过特定子键进行访问,python,dictionary,nested,Python,Dictionary,Nested,我想知道以下字典中的哪个键属于特定子键: 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'

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

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

有更简单/更好的方法吗?

试试这个

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
试试这个

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

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

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

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

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

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

'key2'

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

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

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

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

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

'key2'


[k表示k,v表示dic.items()中的v,如果v.values()中的“entry4”]
?基本上是相同的逻辑,但更紧凑一些。如果你经常通过
name
查找,你可能需要将你的dict反转为
name
键来进行O(1)查找。
下一步(如果dic[i]['name']=='entry4')
@superbrain
dic[i],则dic中的i为i。
获取('name')将更加健壮。如果没有匹配项,可以使用默认参数
next
。@masterofuppets您能确认只想用“name”键搜索值吗?在这种情况下,有些答案是错误的<代码>[k代表k,v代表dic.items()中的v,如果v.values()中的“entry4”]?基本上是相同的逻辑,但更紧凑一些。如果你经常通过
name
查找,你可能需要将你的dict反转为
name
键来进行O(1)查找。
下一步(如果dic[i]['name']=='entry4')
@superbrain
dic[i],则dic中的i为i。
获取('name')将更加健壮。如果没有匹配项,可以使用默认参数
next
。@masterofuppets您能确认只想用“name”键搜索值吗?在这种情况下,有些答案是错误的!使用
''的原因是什么。在这里加入
?@Bill只是为了在列表中删除它OP想要的是唯一的单词
键2
而不是列表中包含的单词如果您得到重复的
键2key3key4…
。我认为@Samwise在评论中有最好的答案。返回一个列表,然后您就可以检测并处理重复项。您可以将分隔符更改为
'
'\n'
使用
''的原因是什么。在此处加入
?@Bill只需将其删除在列表中OP需要唯一的单词
键2
而不是列表中包含的单词。如果您得到重复项,则存在危险
key2key3key4…
。我认为@Samwise在评论中有最好的答案。返回一个列表,然后您就可以检测并处理重复项。您可以将分隔符更改为
'
'\n'
这实际上是不正确的,因为OP只想搜索以
'name'
为键的值。这实际上是不正确的,因为OP只想搜索带有
“name”
作为键。