Search for specific value in list of dictionaries and return the Index
Searching list of dictionaries :
Let’s define a list of dictionaries for our operations.
1 |
list_of_dict = [{'expires': '1800', 'timestamp': '2017-10-04 13:59:09', 'fromUser': 'sip:5545@1.5.7.23:5060', 'callID': '42259bfc-506d3c0e-59d4e928@1.5.2.23'}, {'expires': '1800', 'timestamp': '2017-10-04 13:59:09', 'fromUser': 'sip:5545@19.9.7.29:5060', 'callID': '42259bfc-506d3c0e-59d4e928@19.9.7.29'}, {'expires': '120', 'timestamp': '2017-10-04 13:59:38', 'fromUser': 'sip:ast@19.9.7.7', 'callID': '389c0af66b44f30469eab6793fa4b61b@19.9.7.29'} |
Now I want to search for callID dictionary member in above list of dictionaries. I can use python built-in any function like below.
1 |
any(d['callID'] == '42259bfc-506d3c0e-59d4e928@19.9.7.29' for d in data) |
Above function gives True if it found the callID 42259bfc-506d3c0e-59d4e928@19.9.7.29 in List otherwise it will give False
Here is the small piece of code to search for specific value in list of dictionaries and return the Index
Search for the specific value in the list of dictionaries and return the Index :
1 2 3 4 5 |
def find(lst, key, value): for i, dic in enumerate(lst): if dic[key] == value: return i return -1 |
on success, find function returns the dictionary index in the list. On failure, it will return -1.