This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 7 years ago.
I have a list which looks like this:
some_list = [{'id':1, 'name':'Steve', 'age':23}, {'id':2, 'name':'John', 'age':17}, {'id':3, 'name':'Matt', 'age':31}]
I would like to sort the list my the name value in the dictionary. So Instead of the above order, it would be John then Matt then Steve.
How would I go about this? Thanks.
You can use operator.itemgetter:
>>> import operator
>>> some_list = [dict(id=1, name='Steve', age=23), dict(id=2, name='John', age=17), dict(id=3, name='Matt', age=31)]
>>> sorted(some_list, key=operator.itemgetter('name'))
[{'id': 2, 'age': 17, 'name': 'John'}, {'id': 3, 'age': 31, 'name': 'Matt'}, {'id': 1, 'age': 23, 'name': 'Steve'}]
Or a lambda function:
>>> some_list = [dict(id=1, name='Steve', age=23), dict(id=2, name='John', age=17), dict(id=3, name='Matt', age=31)]
>>> sorted(some_list, key=lambda x: x['name'])
[{'id': 2, 'age': 17, 'name': 'John'}, {'id': 3, 'age': 31, 'name': 'Matt'}, {'id': 1, 'age': 23, 'name': 'Steve'}]
Related
This question already has answers here:
Unique list of dicts based on keys
(10 answers)
Closed 5 months ago.
Given list of dicts:
[{'id': 1, 'name': 'Sam'}, {'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Mark'}, {'id': 2, 'name': 'Jane'}]
Need to turn it into:
[{'id': 1, 'name': 'Sam'}, {'id': 2, 'name': 'Jane'}]
Just take any "record" unique by id. How can i do it in single line ?
Using itertools.groupby, it is assumed that dictionaries with the same id are arranged consecutively:
>>> lst
[{'id': 1, 'name': 'Sam'},
{'id': 1, 'name': 'Bob'},
{'id': 2, 'name': 'Mark'},
{'id': 2, 'name': 'Jane'}]
>>> from itertools import groupby
>>> from operator import itemgetter
>>> [next(mappings) for _, mappings in groupby(lst, key=itemgetter('id'))]
[{'id': 1, 'name': 'Sam'}, {'id': 2, 'name': 'Mark'}]
Or dictionary comprehension:
>>> list({mp['id']: mp for mp in lst}.values())
[{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Jane'}]
This is my data set, this is the column I separated from the csv file.
0 [{'id': 16, 'name': 'Animation'}, {'id': 35, '...
1 [{'id': 12, 'name': 'Adventure'}, {'id': 14, '...
2 [{'id': 10749, 'name': 'Romance'}, {'id': 35, ...
3 [{'id': 35, 'name': 'Comedy'}, {'id': 18, 'nam...
4 [{'id': 35, 'name': 'Comedy'}]
How to get just a list with the content ['Animation', 'Adventure', 'Romance', 'Comedy', 'Comedy'] as output?
I guess you want to see something like that.
list_of_items = [[{'id': 16, 'name': 'Animation'}, {'id': 16, 'name': 'Animation2'}],[{'id': 16, 'name': 'Animation3'}, {'id': 16, 'name': 'Animation4'}]]
output_list = []
for item in list_of_items:
for dict in item:
output_list.append(dict['name'])
Output:
>>> print(output_list)
['Animation', 'Animation2', 'Animation3', 'Animation4']
I don't know if you made a typo but you have some errors with the ' in what you wrote.
But nevertheless from what I can see you have a list with dictionaries. So we loop through that list to access each dictionary and select what in the dictionary we want and append it to the list you created:
d = [{'id': 10749, 'name': 'Romance'}, {'id': 35, 'name': 'Comedy'}]
list_1 = []
for el in d:
list_1.append(el['name'])
print(list_1)
The output will be: ['Romance', 'Comedy']
It's unclear if you have a list of lists or just one list.
For a single list you can use a list comprehension:
dict_list = [{'id': 10749, 'name': 'Romance'}, {'id': 35, 'name': 'Comedy'}]
[dict_item['name'] for dict_item in dict_list]
Otherwise, you can unnest the first list and then do a list comprehension
dict_list = [[{'id': 1, 'name': 'Animation'}, {'id': 2, 'name': 'Comedy'}],[{'id': 3, 'name': 'Romance'}, {'id': 4, 'name': 'Comedy'}]]
[dict_item['name'] for dict_item in [dict_item for sublist in dict_list for dict_item in sublist]]
This question already has answers here:
Extract dict value from list of dict? [duplicate]
(3 answers)
Closed 3 years ago.
How do I find and print the name and age of 'id' == 52? Is using a for loop the only way?
name_list = [
{'id': 11, 'name': 'John', 'Age': 22},
{'id': 52, 'name': 'Mary', 'Age': 25},
{'id': 9, 'name': 'Carl', 'Age': 55 }
]
What you are looking for is a standard loop through a list.
for i in name_list:
if i['id'] == 52:
print(i['name'])
print(i['Age'])
The quickest way I can think of is to use a loop in list comprehension form:
In [1]: [x for x in name_list if x['id'] == 52]
Out[1]: [{'id': 52, 'name': 'Mary', 'Age': 25}]
I m trying to sort a list of dict using sorted
>>> help(sorted)
Help on built-in function sorted in module __builtin__:
sorted(...)
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
I have just given list to sorted and it sorts according to id.
>>>l = [{'id': 4, 'quantity': 40}, {'id': 1, 'quantity': 10}, {'id': 2, 'quantity': 20}, {'id': 3, 'quantity': 30}, {'id': 6, 'quantity': 60}, {'id': 7, 'quantity': -30}]
>>> sorted(l) # sorts by id
[{'id': -1, 'quantity': -10}, {'id': 1, 'quantity': 10}, {'id': 2, 'quantity': 20}, {'id': 3, 'quantity': 30}, {'id': 4, 'quantity': 40}, {'id': 6, 'quantity': 60}, {'id': 7, 'quantity': -30}]
>>> l.sort()
>>> l # sorts by id
[{'id': -1, 'quantity': -10}, {'id': 1, 'quantity': 10}, {'id': 2, 'quantity': 20}, {'id': 3, 'quantity': 30}, {'id': 4, 'quantity': 40}, {'id': 6, 'quantity': 60}, {'id': 7, 'quantity': -30}]
Many example of sorted says it requires key to sort the list of dict. But I didn't give any key. Why it didn't sort according to quantity? How did it choose to sort with id?
I tried another example with name & age,
>>> a
[{'age': 1, 'name': 'john'}, {'age': 3, 'name': 'shyam'}, {'age': 30,'name': 'ram'}, {'age': 15, 'name': 'rita'}, {'age': 5, 'name': 'sita'}]
>>> sorted(a) # sorts by age
[{'age': 1, 'name': 'john'}, {'age': 3, 'name': 'shyam'}, {'age': 5, 'name':'sita'}, {'age': 15, 'name': 'rita'}, {'age': 30, 'name': 'ram'}]
>>> a.sort() # sorts by age
>>> a
[{'age': 1, 'name': 'john'}, {'age': 3, 'name': 'shyam'}, {'age': 5, 'name':'sita'}, {'age': 15, 'name': 'rita'}, {'age': 30, 'name': 'ram'}]
Here it sorts according to age but not name. What am I missing in default behavior of these method?
From some old Python docs:
Mappings (dictionaries) compare equal if and only if their sorted (key, value) lists compare equal. Outcomes other than equality are resolved consistently, but are not otherwise defined.
Earlier versions of Python used lexicographic comparison of the sorted (key, value) lists, but this was very expensive for the common case of comparing for equality. An even earlier version of Python compared dictionaries by identity only, but this caused surprises because people expected to be able to test a dictionary for emptiness by comparing it to {}.
Ignore the default behaviour and just provide a key.
By default it will compare against the first difference it finds. If you are sorting dictionaries this is quite dangerous (consistent yet undefined).
Pass a function to key= parameter that takes a value from the list (in this case a dictionary) and returns the value to sort against.
>>> a
[{'age': 1, 'name': 'john'}, {'age': 3, 'name': 'shyam'}, {'age': 30,'name': 'ram'}, {'age': 15, 'name': 'rita'}, {'age': 5, 'name': 'sita'}]
>>> sorted(a, key=lambda d : d['name']) # sorts by name
[{'age': 1, 'name': 'john'}, {'age': 30, 'name': 'ram'}, {'age': 15, 'name': 'rita'}, {'age': 3, 'name': 'shyam'}, {'age': 5, 'name': 'sita'}]
See https://wiki.python.org/moin/HowTo/Sorting
The key parameter is quite powerful as it can cope with all sorts of data to be sorted, although maybe not very intuitive.
I have a list like this:
li = [
{
'name': 'Lee',
'age': 22
},
{
'name': 'Mike',
'age': 34
},
{
'name': 'John',
'age': 23
}
]
I want sort the list with sorted method, and sort by the the age key
How to achieve it?
Use a key function:
li_sorted = sorted(li, key=lambda x: x['age'])
The Python3 equivalent of what #kojiro suggests is this
>>> sorted(li, key=lambda x:sorted(x.items()))
[{'age': 22, 'name': 'Lee'}, {'age': 23, 'name': 'John'}, {'age': 34, 'name': 'Mike'}]
Clearly this is less efficient than
>>> sorted(li, key=lambda x:x['age'])
[{'age': 22, 'name': 'Lee'}, {'age': 23, 'name': 'John'}, {'age': 34, 'name': 'Mike'}]
anyway. There is also the advantage that it doesn't rely on the fact that 'age' < 'name'
Here's how to write the same thing using itemgetter
>>> from operator import itemgetter
>>> sorted(li, key=itemgetter('age'))
[{'age': 22, 'name': 'Lee'}, {'age': 23, 'name': 'John'}, {'age': 34, 'name': 'Mike'}]