Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find a value in a list of python dictionaries?

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() 
like image 224
bobsr Avatar asked Jun 17 '13 14:06

bobsr


People also ask

How do I find an item in a list Python?

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.

How do you get a value from a dictionary into a list?

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.

How do I find something in a dictionary Python?

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.


1 Answers

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.

like image 51
Martijn Pieters Avatar answered Sep 26 '22 01:09

Martijn Pieters