字典中键的顺序

时间:2011-04-12 00:21:38

标签: python dictionary

代码:

d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()

print l

这会打印['a', 'c', 'b']。我不确定方法keys()如何确定 l 中关键字的顺序。但是,我希望能够以“正确”的顺序检索关键字。正确的顺序当然会创建列表['a', 'b', 'c']

6 个答案:

答案 0 :(得分:66)

您可以使用OrderedDict(需要Python 2.7)或更高版本。

另请注意,OrderedDict({'a': 1, 'b':2, 'c':3})无效,因为您使用dict创建的{...}已经忘记了元素的顺序。相反,您想使用OrderedDict([('a', 1), ('b', 2), ('c', 3)])

如文档中所述,对于低于Python 2.7的版本,您可以使用this配方。

答案 1 :(得分:55)

Python 3.7 +

在Python 3.7.0中,dict个对象has been declared的插入顺序保存性质是Python语言规范的官方部分。因此,你可以依赖它。

Python 3.6(CPython)

从Python 3.6开始,对于Python的CPython实现,默认情况下为词典maintain insertion order。这被认为是一个实现细节;如果你想要在其他Python实现中保证插入排序,你仍然应该使用collections.OrderedDict

Python> = 2.7和< 3.6

当您需要dict时,请使用collections.OrderedDict课程 记住插入的项目的顺序。

答案 2 :(得分:43)

>>> print sorted(d.keys())
['a', 'b', 'c']

使用sorted function对传入的迭代进行排序。

.keys()方法以任意顺序返回键。

答案 3 :(得分:12)

来自http://docs.python.org/tutorial/datastructures.html

“字典对象的keys()方法以任意顺序返回字典中使用的所有键的列表(如果要对其进行排序,只需对其应用sorted()函数)。”

答案 4 :(得分:11)

只要您想要使用它就对列表进行排序。

l = sorted(d.keys())

答案 5 :(得分:0)

尽管顺序无关紧要,因为字典是哈希图。这取决于将其推入的顺序:

s = 'abbc'
a = 'cbab'

def load_dict(s):
    dict_tmp = {}
    for ch in s:
        if ch in dict_tmp.keys():
            dict_tmp[ch]+=1
        else:
            dict_tmp[ch] = 1
    return dict_tmp

dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))

输出:
    对于字符串abbc,键为dict_keys(['a','b','c'])
    对于字符串cbab,键为dict_keys(['c','b','a'])

相关问题