This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 8 years ago.
I have list:
[
{'name': 'peter', 'age': 41, 'value': 1},
{'name': 'jon', 'age': 31, 'value': 5},
{'name': 'alan', 'age': 23, 'value': 3}
]
How to sort this list by 'age'?
You can use a lambda function and one of the following functions to sort:
If you want to sort in-place (modify the list):
L.sort(key = lambda d:d['age'])
If you want to create a new sorted list:
print sorted(L, key = lambda d:d['age'])
Related
I am trying to update the values of the dictionary as the values provided by another list, but the update is happening to all of the previous values as well.
Here is my code snippet:
dict = {'name' : 'shubham', 'age': 23}
listDict = [dict]*5
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
Output is coming :
[{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23},
{'name': 'shubha', 'age': 23}]
It should be coming :
[{'name': 'sh', 'age': 23},
{'name': 'shu', 'age': 23},
{'name': 'shub', 'age': 23},
{'name': 'shubh', 'age': 23},
{'name': 'shubha', 'age': 23}]
When you do the [dict]*5 operation, what you have afterwards is a list of 5 references to the same dictionary object in memory, thus when you edit one you are actually editing all of them. For more explanation of this, look up the difference between Mutable and Immutable objects in python (this occurs because dictionaries are mutable).
To accomplish what you want, you need to explicitly make copies of the initial dict.
listDict = [dict.copy() for i in range(5)]
This should create the result you expect.
(also friendly tip: your should avoid naming your first dictionary dict: that shadows the dict() function and is confusing to read!)
If you create a list of dictionaries like this: [dict]*5 the dictionaries will be linked to each other.
So I suggest you to do the multiplication this way:
dict = {'name' : 'shubham', 'age': 23}
listDict = [ dict.copy() for i in range(5) ]
names = ['sh', 'shu', 'shub', 'shubh', "shubha"]
print(listDict)
for ind, dic in enumerate(listDict):
listDict[ind]['name'] = names[ind]
print(listDict)
Hope I helped!
This question already has answers here:
Getting a few values out of dictionary with default different than None (Python)
(2 answers)
Closed 2 years ago.
In the following example I iterate through a list of dictionaries and I save the 'age' on a list. However, the second dictionary does not have the key 'age'. In that case I would like the value null to be saved on the list. Any suggetsions on how to achieve this?
my_list = [{'age': 0, 'name': 'A'}, {'name': 'B'}, {'age': 2, 'name': 'C'}, {'age': 3, 'name': 'D'}, {'age': 4, 'name': 'E'}, {'age': 5, 'name': 'F'}]
ages = [li['age'] for li in my_list]
You can use dict.get(key, default_value) method, If the key not exist it will return default value. If you don't set default value it will return None
ages = [li.get('age', 0) for li in my_list]
This question already has answers here:
How do I sort a list of dictionaries by a value of the dictionary?
(20 answers)
Closed 2 years ago.
Write a Python program to sort a list of dictionaries using Lambda
device_models = [{'make':'Asus', 'model':216, 'color':'Black'}, {'make':'NOKIA', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}]
device_models = [{'make':'Asus', 'model':216, 'color':'Black'}, {'make':'NOKIA', 'model':'2', 'color':'Gold'}, {'make':'Samsung', 'model': 7, 'color':'Blue'}]
print("Original list of dictionaries :")
print(device_models)
# to sort a list of dictionaries using Lambda
sorted_models = sorted(device_models, key = lambda x: x['color'])
print("\nSorting the List of dictionaries :")
print(sorted_models)
O/P:-
Original list of dictionaries :
[{'make': 'Asus', 'model': 216, 'color': 'Black'}, {'make': 'NOKIA', 'model': '2', 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}]
Sorting the List of dictionaries :
[{'make': 'Asus', 'model': 216, 'color': 'Black'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}, {'make': 'NOKIA', 'model': '2', 'color': 'Gold'}]
I have a nested dictionary
d = {'records':[
{'name':abhi,'age':23,'dept':'cse'},
{'name':anu,'age':20,'dept':'ece'},
{'name':ammu,'age':25,'dept':'cse'},
{'name':anju,'age':26,'dept':'ece'}
]}
but I want to have the dictionary rearranged, grouped by department. I have done different methods, but did not get the desired result.
d = [
[ {'name':abhi,'age':23,'dept':'cse'},
{'name':ammu,'age':25,'dept':'cse'}
],
[ {'name':anu,'age':20,'dept':'ece'},
{'name':anju,'age':26,'dept':'ece'}
]
]
Any help would be appreciated.
What you have is a list of dictionaries within a dictionary. You can sort these dictionaries using standard list sorting methods:
d={'records':[{'name':'abhi','age':23,'dept':'cse'},
{'name':'anu','age':20,'dept':'ece'},
{'name':'ammu','age':25,'dept':'cse'},
{'name':'anju','age':26,'dept':'ece'}]}
d['records'].sort(key = lambda x: x['name'])
>>> d['records']
[{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}, {'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}]
For your particular case:
d['records'].sort(key = lambda x: (x['name'], x['dept']))
And then a list comprehension to group sublists with the same dept together:
my_list = [[i for i in d['records'] if i['dept'] == de] for de in {i['dept'] for i in d['records']}]
>>> my_list
[[{'name': 'anju', 'age': 26, 'dept': 'ece'}, {'name': 'anu', 'age': 20, 'dept': 'ece'}], [{'name': 'abhi', 'age': 23, 'dept': 'cse'}, {'name': 'ammu', 'age': 25, 'dept': 'cse'}]]
This question already has answers here:
Remove duplicate dict in list in Python
(16 answers)
Closed 6 years ago.
I have a list of dictionaries
l = [
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'john', 'surname': 'smith'},
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'jane', 'surname': 'bloggs'}
]
how do i remove duplicates i.e. {'firstname': 'joe', 'surname': 'bloggs'} appears twice so would want it only appearing once?
Something like this should do the stuff :
result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in l)]
first, I transform the inital dict in a list of tuples, then I put them into a set (that removes duplicates entries), and then back into a dict.
import itertools
import operator
from operator import itemgetter
import pprint
l = [
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'john', 'surname': 'smith'},
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'jane', 'surname': 'bloggs'}
]
getvals = operator.itemgetter('firstname', 'surname')
l.sort(key=getvals)
result = []
for k, g in itertools.groupby(l, getvals):
result.append(g.next())
l[:] = result
pprint.pprint(l)