Python: Python:Sort 字典中的值?
Python: Python:Sort values in dictionary?
我有
x = {2:[40,30],3:[24,16],4:[30,2],5:[0,80],6:[19,8]}
我需要根据值中的第一项对字典进行排序
所以我的结果应该是
{2:[40,30],4:[30,2],3:[24,16],6:[19,8],5:[0,80]}
只需将其传递给 dict()
:
>>> dict([(2, [40, 30]), (4, [30, 2])])
{2: [40, 30], 4: [30, 2]}
字典不关心它们的值的顺序:
>>> {'one': 1, 'two': 2} == {'two': 2, 'one': 1}
True
如果要维持秩序,可以使用collections.OrderedDict
:
>>> from collections import OrderedDict
>>> OrderedDict([(2, [40, 30]), (4, [30, 2])])
OrderedDict([(2, [40, 30]), (4, [30, 2])])
您只需使用 dict
d = dict(x)
因为您的 list
已经是可以轻松转换为 Dictionary
的正确格式,也就是说,您已经有一个 key-value
元组对作为您的列表元素。
您的问题没有明确说明,但根据您对其他答案的评论,您希望以字典形式保留列表的顺序。标准字典本质上是无序的,但是,您可以使用 OrderedDict
代替:
from collections import OrderedDict
x = [(4, [30, 2]), (2, [40, 30])]
d = dict(x)
print(d)
# {2: [40, 30], 4: [30, 2]}
d = OrderedDict(x)
print(d)
# OrderedDict([(4, [30, 2]), (2, [40, 30])])
这会按照添加到字典的顺序保留键。
我有
x = {2:[40,30],3:[24,16],4:[30,2],5:[0,80],6:[19,8]}
我需要根据值中的第一项对字典进行排序 所以我的结果应该是
{2:[40,30],4:[30,2],3:[24,16],6:[19,8],5:[0,80]}
只需将其传递给 dict()
:
>>> dict([(2, [40, 30]), (4, [30, 2])])
{2: [40, 30], 4: [30, 2]}
字典不关心它们的值的顺序:
>>> {'one': 1, 'two': 2} == {'two': 2, 'one': 1}
True
如果要维持秩序,可以使用collections.OrderedDict
:
>>> from collections import OrderedDict
>>> OrderedDict([(2, [40, 30]), (4, [30, 2])])
OrderedDict([(2, [40, 30]), (4, [30, 2])])
您只需使用 dict
d = dict(x)
因为您的 list
已经是可以轻松转换为 Dictionary
的正确格式,也就是说,您已经有一个 key-value
元组对作为您的列表元素。
您的问题没有明确说明,但根据您对其他答案的评论,您希望以字典形式保留列表的顺序。标准字典本质上是无序的,但是,您可以使用 OrderedDict
代替:
from collections import OrderedDict
x = [(4, [30, 2]), (2, [40, 30])]
d = dict(x)
print(d)
# {2: [40, 30], 4: [30, 2]}
d = OrderedDict(x)
print(d)
# OrderedDict([(4, [30, 2]), (2, [40, 30])])
这会按照添加到字典的顺序保留键。