简体   繁体   中英

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' . 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 . This turns out to be a list, as per Daniel F below!

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(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:

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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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