【发布时间】:2018-04-21 13:56:57
【问题描述】:
所以我需要将我的字典转换为按值排序的字典:
from collections import OrderedDict
from collections import OrderedDict
import json
d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
# OrderedDict([('first': 1), ('second': 2), ('third': 3), ('fourth': 4)])
# print (OrderedDict)
def ordereddict_to_dict(d_sorted_by_value):
for k, v in d_sorted_by_value.items():
if isinstance(v, dict):
d_sorted_by_value[k] = ordereddict_to_dict(v)
print dict(d_sorted_by_value)
d = {"third": 3, "first": 1, "fourth": 4, "second": 2}
d_sorted_by_value = OrderedDict(sorted(d.items(), key=lambda x: x[1]))
print d_sorted_by_value
ordereddict_to_dict(d_sorted_by_value)
打印 d_sorted_by_value 我得到:
OrderedDict([('first', 1), ('second', 2), ('third', 3), ('fourth', 4)])
这不是我想要的,即使它可以用作字典。 所以将其转换为 dict 的函数被调用,它给了我以下输出:
{'second': 2, 'third': 3, 'fourth': 4, 'first': 1}
正如您所见,键值对:'first':1' 是转换时的最后一个元素,我在这里做什么?我想要的输出是:
{'first': 1,'second': 2, 'third': 3, 'fourth': 4}
请引导正确的方向。谢谢!!
【问题讨论】:
-
字典不是有序的数据结构。这就是 OrderedDict 存在的原因!
标签: python python-2.7 dictionary ordereddictionary