I have a dictionary like this:
Averages = {'Jennifer': [1],'Chris': [5],'Malcolm': [9]}
I want to change and sort that dictionary (not make a new one) into this:
Averages = {'Malcolm': 9, 'Chris': 5, 'Jennifer': 1}
How would I do this?
Merging both answers together, you should have something like this with an OrderedDict
import operator
from collections import OrderedDict
Averages = {'Jennifer': [1],'Chris': [5],'Malcolm': [9]}
Averages ={k:v[0] for k,v in Averages.items()}
Averages = OrderedDict(sorted(Averages.items(), key=operator.itemgetter(1), reverse=True))
You can use dictionary comprehension
>>> Averages2 ={k:v[0] for k,v in Averages.items()}
>>> Averages2
{'Chris': 5, 'Malcolm': 9, 'Jennifer': 1}
Dictionaries in python are declared unordered, they don't have order. Because of that you just can't push them to save the order. You can try to create a dict from any ordered object, and it will loose its order, so just forget about that. If you want ordering, use different types, like list or ordered dict .
@Joe К answered you, how to make your dict to be a dict of integers, not lists. If you want to get list of its ordered items, try this:
>>>import operator
>>> A = sorted(Averages.items(), key=operator.itemgetter(1))
>>> A
[('Jenifer', 1), ('Chris', 5), ('Malcolm', 9)]
If you think, that this is the order you needed - then good. If you still insist of having those items ordered in dictionary - try it:
>>> dict(A)
{'Chris': 5, 'Malcolm': 9, 'Jenifer': 1}
It is not possible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.