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.
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 .
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.
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.
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 .
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]
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'}]
>>>
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