Reputation: 21
i have a list of dicts
[{"id":1, "name": "jane", "contact": {"email": "[email protected]", "phone": "8179482938"}},
{"id":2, "name": "john", "contact": {"email": "[email protected]", "phone": "8179482937"}},
{"id":3, "name": "june", "contact": {"email": "[email protected]", "phone": "8179482936"}}]
how can i find the index of jane given only her phone number (8179482938)?
Upvotes: 0
Views: 42
Reputation: 54698
It's rather straightforward. You loop through the list until you find the one you want.
def get_name(phone):
for i, row in enumerate(list_of_dicts):
if row['contact']['phone'] == phone:
return i
Upvotes: 1
Reputation: 195438
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
Upvotes: 0
Reputation: 7716
This:
book = [{"id":1, "name": "jane", "contact": {"email": "[email protected]", "phone": "8179482938"}},
{"id":2, "name": "john", "contact": {"email": "[email protected]", "phone": "8179482937"}},
{"id":3, "name": "june", "contact": {"email": "[email protected]", "phone": "8179482936"}}]
for item in book:
if item['contact']['phone'] == '8179482938':
print(item['id'])
Upvotes: 0