Skip to content
Advertisement

Find the index of a nested dict within a list base on the dict’s nested value

i have a list of dicts

[{"id":1, "name": "jane", "contact": {"email": "jane@gmail.com", "phone": "8179482938"}},
{"id":2, "name": "john", "contact": {"email": "john@gmail.com", "phone": "8179482937"}},
{"id":3, "name": "june", "contact": {"email": "june@gmail.com", "phone": "8179482936"}}]

how can i find the index of jane given only her phone number (8179482938)?

Advertisement

Answer

To get an index, you can do (lst is your list from question):

idx = next(i for i, d in enumerate(lst) if d["contact"]["phone"] == "8179482938")
print(idx)

Prints:

0
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement