[英]How do I turn a dictionary with lists as values into a dictionary with integers as values?
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将两个答案合并在一起,您应该使用 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
您可以使用
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. python中的字典被声明为无序的,它们没有顺序。 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.
你可以尝试从任何有序对象创建一个 dict,它会失去它的顺序,所以忘记这一点。 If you want ordering, use different types, like list or ordered dict .
如果您想要排序,请使用不同的类型,例如 list 或ordered dict 。
@Joe К answered you, how to make your dict to be a dict of integers, not lists. @Joe К 回答您,如何使您的 dict 成为整数 dict,而不是列表。 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.这不可能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.