Python字典排序

时间:2013-02-10 10:01:51

标签: python sorting dictionary

我有一个像

这样的词典
>>> x = {'a':2, 'c': 1, 'b':3}

字典中没有可用的方法按值对字典进行排序。我用

对它进行了分类
>>> sorted_x = sorted(x.iteritems(), key=operator.itemgetter(1))
>>> sorted_x
[('c', 1), ('a', 2), ('b', 3)]

但现在我通过循环再次将sorted_x转换为字典。像

>>> new_dict = {}
>>> for i in sorted_x:
    new_dict[i[0]] = i[1]
>>> new_dict
{'a': 2, 'c': 1, 'b': 3}

new_dict再次保持未分类状态。为什么python字典不能按键排序?任何人都可以阐明它。

2 个答案:

答案 0 :(得分:3)

字典未分类。它们只是键和值之间的映射。

如果您需要排序字典,请使用collections.OrderedDict

>>> import collections
>>> d = collections.OrderedDict(sorted_x)
>>> d
    OrderedDict([('c', 1), ('a', 2), ('b', 3)])
>>> d['c']
    1

答案 1 :(得分:2)

python中的字典是哈希映射。对密钥进行哈希处理,以便快速访问元素。

这意味着元素内部必须根据它们生成的哈希进行排序,而不是取决于您想要的顺序。

相关问题