将已排序的ordereddict转换为dict时,键值对位置发生变化

时间:2018-04-21 13:56:57

标签: python python-2.7 dictionary ordereddictionary

所以我需要将字典转换为按值排序的字典:

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的函数叫做whch给了我以下输出:

{'second': 2, 'third': 3, 'fourth': 4, 'first': 1}

正如你可以看到键值对:'first':1'转换为最后一个元素,我在做什么?我想要的所需输出是:

{'first': 1,'second': 2, 'third': 3, 'fourth': 4}

请指导正确的方向。谢谢!

1 个答案:

答案 0 :(得分:1)

你所要求的是不可能的。

Python< 3.7中的dict对象不被视为已订购。它在3.6内部排序,但这被认为是一个实现细节。

不应假设将dict转换为OrderedDict然后再转换回dict对象以保持顺序。

您的选择是:

  1. 使用常规dict作为无序集合。
  2. 使用OrderedDict作为有序集合。
相关问题