Have a list of python dictionaries in the following format. How would you do a search to find a specific name exists?
label = [{'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), 'name': 'Test', 'pos': 6}, {'date': datetime.datetime(2013, 6, 17, 8, 56, 24, 2347), 'name': 'Name 2', 'pos': 1}]
The following did not work:
if 'Test' in label[name] 'Test' in label.values()
To find an element in the list, use the Python list index() method, The index() is an inbuilt Python method that searches for an item in the list and returns its index. The index() method finds the given element in the list and returns its position.
To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.
To simply check if a key exists in a Python dictionary you can use the in operator to search through the dictionary keys like this: pets = {'cats': 1, 'dogs': 2, 'fish': 3} if 'dogs' in pets: print('Dogs found!') # Dogs found! A dictionary can be a convenient data structure for counting the occurrence of items.
You'd have to search through all dictionaries in your list; use any()
with a generator expression:
any(d['name'] == 'Test' for d in label)
This will short circuit; return True
when the first match is found, or return False
if none of the dictionaries match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With