'Get nested dictonary name by value

I want to get the nested dictionary value by inputting a value in the said nested dictonary

example

users = {"Pepe": {"Name": "Pepe Perez", "ID": "A1234"}, "Juan": {"Name": "Gomez", "ID": "B4321"}}
find-name = input("enter id: ")

so if the input is "B4321" it should return "Juan" Any idea of how to do it? Thanks



Solution 1:[1]

You can make a generator expression that loops through the dict's items until it finds a value matching your ID. Then return the next one. This assumes only one item matches:

users = {"Pepe": {"Name": "Pepe Perez", "ID": "A1234"}, "Juan": {"Name": "Gomez", "ID": "B4321"}}
find_name = "B4321"

next((k for k, v in users.items() if v['ID'] == find_name), None)
# 'Juan'

This will return None if the id is not found. This would be more efficient if you used the ID value as the key for the main dict. Then you could just look it up.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mark