Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter list of dictionaries

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".

like image 414
Den Contre Avatar asked Sep 09 '15 07:09

Den Contre


People also ask

How do I filter a dictionary list in Python?

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 .

Can you filter dictionaries in Python?

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 .

How do I sort a list of dictionaries in Python?

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.

Can Python have a list of dictionaries?

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.


1 Answers

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']
like image 112
Sdwdaw Avatar answered Oct 16 '22 21:10

Sdwdaw