Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter list of dictionaries with matching values for a given key

With an interface like a = copyf(dictlist, key, valuelist).

>>> dictlist = [{'first': 'James',
                 'last': 'Joule'},
                {'first': 'James',
                 'last': 'Watt'},
                {'first': 'Christian',
                 'last': 'Doppler'}]
>>> valuelist = ['James', 'John']
>>> x = copyf(dictlist, 'first', valuelist)
>>> print(x)
[{'first': 'James',
  'last': 'Joule'},
 {'first': 'James',
  'last': 'Watt'}]

The dictlist is effectively a csv.DictReader instance.

like image 268
Christopher O'Donnell Avatar asked Apr 23 '11 06:04

Christopher O'Donnell


People also ask

How do you filter a dictionary list?

Solution: Use list comprehension [x for x in lst if condition(x)] to create a new list of dictionaries that meet the condition. All dictionaries in lst that don't meet the condition are filtered out. You can define your own condition on list element x .

How do I sort a list of dictionaries by key?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

How do you check if two dictionaries have the same keys and values?

Check if two nested dictionaries are equal in Python To do this task, we are going to use the == operator and this method will help the user to check whether the two given dictionaries are equal or not.

How do you find the values of a key in a list of dictionaries in Python?

Use a list comprehension to find the values of a key in a list of dictionaries. Use the list comprehension syntax [dict[key] for dict in list_of_dicts] to get a list containing the corresponding value for each occurrence of key in the list of dictionaries list_of_dicts .


2 Answers

Update: taking into account the reedited question of the OP:

def copyf(dictlist, key, valuelist):
      return [dictio for dictio in dictlist if dictio[key] in valuelist]
like image 73
joaquin Avatar answered Oct 19 '22 00:10

joaquin


Probably not the best solution, but here we go:

>>> def copyf(data, key, allowed):
...     return filter(lambda x: key in x and x[key] in allowed, data)
... 
>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> copyf(dictlist, 'first', ('Christian',))
[{'last': 'Doppler', 'first': 'Christian'}]
>>> copyf(dictlist, 'last', ('Christian',))
[]
>>> copyf(dictlist, 'first', ('James',))
[{'last': 'Joule', 'first': 'James'}, {'last': 'Watt', 'first': 'James'}]
>>> 
like image 6
plaes Avatar answered Oct 19 '22 00:10

plaes