【问题标题】:key value pair position change when converting sorted ordereddict to dict将有序dict转换为dict时键值对位置发生变化
【发布时间】: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


【解决方案1】:

你的要求是不可能的。

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

不应假定将dict 转换为OrderedDict 再转换回dict 对象以维持秩序。

您的选择是:

  1. 对无序集合使用常规 dict
  2. 对有序集合使用OrderedDict

【讨论】:

  • 是否可以将字典上的最后一个键值对附加到字典的开头?如果可以,怎么做?
  • @CouchPotato95,不,这是不可能的。在 Python 3.7 之前,字典不被认为是有序的。使用OrderedDict 而不转换回dict
猜你喜欢
  • 2021-04-18
  • 2012-10-28
  • 2023-03-14
  • 2021-03-29
  • 1970-01-01
  • 2021-02-04
  • 2021-05-19
  • 1970-01-01
  • 2012-10-15
相关资源
最近更新 更多