This is my example:
dictlist = [{'first': 'James', 'last': 'Joule'},
{'first': 'James','last': 'Watt'},
{'first': 'Christian','last': 'Doppler'}]
I am trying to get the last name. If this was in a model, the code would be:
getdata = Name.objects.filter(name="Christian")
getLastName = getdata.last
and I would get "Doppler"
.
How do I filter a dictionary list in Python? Short answer: The list comprehension statement [x for x in lst if condition(x)] creates 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 .
Filter Python Dictionary By Key Using Generic Function The lambda function you pass returns k%2 == 1 which is the Boolean filtering value associated with each original element in the dictionary names .
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.
In Python, you can have a List of Dictionaries. You already know that elements of the Python List could be objects of any type. In this tutorial, we will learn how to create a list of dictionaries, how to access them, how to append a dictionary to list and how to modify them.
This is very simple solution with list comprehension:
>>> dictlist = [{'first': 'James', 'last': 'Joule'}, {'first': 'James','last': 'Watt'},{'first': 'Christian','last': 'Doppler'}]
>>> [x['last'] for x in dictlist if x['first'] == 'Christian']
['Doppler']
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