Assume a list of dicts, e.g., the following:
a = {'key': 5705435, 'key2': 1, 'data': 'data'}
b = {'key': 2345435, 'key2': 1, 'data': 'data'}
c = {'key': 9155435, 'key2': 2, 'data': 'data'}
data = [a,b,c]
I want to get a dict from that list that matches a given key (e.g. return dict with key == 2345435
or return dict where key == 9155435 and key2 == 2
). Obviously I can iterate through the list and compare the key attributes like below.
def get_dict_by_key(data):
for el in data:
if el['key'] == 2345435:
return el
return None
Is there another method to do this (without explicitly iterating through the list)? Are there some predefined methods, like for example list.index(element)
, where I can pass into incomplete information about the dict I'm looking for?