mardi 24 décembre 2019

Get the parent key if a value is in the nested dictionary

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)])

I acknowledge the fact that am not good at working with dictionaries. Any help and direction would be appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire