简体   繁体   English

如果值在嵌套列表中,则获取父键 (dict_values)

[英]Get the parent key if a value is in the nested list (dict_values)

I have a dictionary that looks like this:我有一本看起来像这样的字典:

{'7D': {'category': 'C', 'directory': 'C', 'name': 'Co'},
 '37': {'category': 'C', 'directory': 'C', 'name': 'FI'},
 'AA': {'category': 'F', 'directory': 'F', 'name': 'Le'},
 '80': {'category': 'Cl', 'directory': 'F', 'name': 'AV'},
 'F7': {'category': 'Cl', 'directory': 'F', 'name': 'AG'}}

I would like to get 7D if lookup_value = 'Co' .如果lookup_value = 'Co'我想得到7D I have tried these two approaches:我已经尝试过这两种方法:

lookup_value = 'Co'
for name, val in groups.items():
    if val == lookup_value:
        print(name)

And this:和这个:

print(list(groups.keys().[list(groups.values()).index(lookup_value)])

The second one returns:第二个返回:

 ValueError: 'Co' is not in list

Edit:编辑:

I am sorry for this mess, I figured that the initial dictionary does not have a nested dictionary.我很抱歉这个烂摊子,我认为初始字典没有嵌套字典。 It turns out that is a list as can be observed from the following:事实证明,这是一个列表,可以从以下内容中观察到:

bbb = groups.values()
type(bbb)

which returns dict_values .返回dict_values This turns out to be a list, as per Daniel F below!事实证明这是一个列表,如下面的 Daniel F 所示!

In general, dictionaries are for one-way lookup.通常,字典用于单向查找。 If you find yourself doing a reverse lookup often, it's probably worth creating and maintaining a reverse dictionary:如果您发现自己经常进行反向查找,则可能值得创建和维护一个反向字典:

groups = {...}
names = {v['name']: k for k, v in groups.items()}

Now it's as simple as accessing现在就像访问一样简单

names['Co']

If you really just want one lookup without creating the reverse dict, use next with a generator:如果您真的只想查找而不创建反向字典,请使用next和生成器:

next(k for k, v in groups.items() if v['name'] == 'Co')

I want to explain why your first approach does not work as intended and provide smallest-change repair.我想解释为什么您的第一种方法不能按预期工作并提供最小更改的修复。 Your groups is dict with keys being str s and values being dict s, thus inside your for-loop:您的groups是 dict ,键是str ,值是dict ,因此在您的 for 循环中:

for name, val in groups.items():

val is dict for example: {'category': 'C', 'directory': 'C', 'name': 'Co'} and asking python about equality ( == ) between str and dict lead to response: No. Correct question: is 'Co' inside dict 's values? valdict例如: {'category': 'C', 'directory': 'C', 'name': 'Co'}并询问 python strdict之间的相等性 ( == ) 导致响应:否。正确的问题: 'Co'dict的值中吗? After changing that, your code will be working:更改后,您的代码将起作用:

lookup_value = 'Co'
for name, val in groups.items():
    if lookup_value in val.values():
        print(name)

Output:输出:

7D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM