问题:字典中键的顺序
码:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l打印['a', 'c', 'b']。我不确定该方法如何keys()确定l中关键字的顺序。但是,我希望能够以“适当”的顺序检索关键字。当然,正确的顺序将创建列表['a', 'b', 'c']。
回答 0
您可以使用OrderedDict(需要Python 2.7)或更高版本。
另外,请注意,OrderedDict({'a': 1, 'b':2, 'c':3})由于dict您使用进行创建的操作{...}已经忘记了元素的顺序,因此该操作无效。相反,您想使用OrderedDict([('a', 1), ('b', 2), ('c', 3)])。
如文档中所述,对于低于python 2.7的版本,可以使用此配方。
回答 1
Python 3.7以上
在Python 3.7.0中,dict对象的插入顺序保留性质已声明为Python语言规范的正式组成部分。因此,您可以依靠它。
Python 3.6(CPython)
从Python 3.6开始,对于Python的CPython实现,字典默认情况下保持插入顺序。但是,这被认为是实现细节。collections.OrderedDict如果希望在其他Python实现中保证插入顺序,则仍应使用。
Python> = 2.7和<3.6
collections.OrderedDict当您需要dict记住插入项目顺序的时,请使用该类。
回答 2
回答 3
只需在要使用列表时对其进行排序。
l = sorted(d.keys())回答 4
来自http://docs.python.org/tutorial/datastructures.html:
“字典对象的keys()方法以任意顺序返回字典中使用的所有键的列表(如果要对其排序,只需对其应用sorted()函数)。”
回答 5
尽管顺序无关紧要,因为字典是哈希图。这取决于将其推入的顺序:
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,键为字符串cbab的dict_keys([‘a’,’b’,’c’])
    对于密钥cbab,键为dict_keys([‘c’,’b’,’a’])

