I have a list of dicts:
list = [{\'id\':\'1234\',\'name\':\'Jason\'},
{\'id\':\'2345\',\'name\':\'Tom\'},
{\'id\':\'3456\',\'name\':\'Art\'}]
A simple readable version is
def find(lst, key, value):
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return -1
One liner!?
elm = ([i for i in mylist if i['name'] == 'Tom'] or [None])[0]
Seems most logical to use a filter/index combo:
names=[{}, {'name': 'Tom'},{'name': 'Tony'}]
names.index(filter(lambda n: n.get('name') == 'Tom', names)[0])
1
And if you think there could be multiple matches:
[names.index(n) for item in filter(lambda n: n.get('name') == 'Tom', names)]
[1]
lst = [{'id':'1234','name':'Jason'}, {'id':'2345','name':'Tom'}, {'id':'3456','name':'Art'}]
tom_index = next((index for (index, d) in enumerate(lst) if d["name"] == "Tom"), None)
# 1
If you need to fetch repeatedly from name, you should index them by name (using a dictionary), this way get operations would be O(1) time. An idea:
def build_dict(seq, key):
return dict((d[key], dict(d, index=index)) for (index, d) in enumerate(seq))
info_by_name = build_dict(lst, key="name")
tom_info = info_by_name.get("Tom")
# {'index': 1, 'id': '2345', 'name': 'Tom'}
def search(itemID,list):
return[i for i in list if i.itemID==itemID]
I needed a more general solution to account for the possibility of multiple dictionaries in the list having the key value, and a straightforward implementation using list comprehension:
dict_indices = [i for i, d in enumerate(dict_list) if d[dict_key] == key_value]