旧版本 Python 中字典中键的顺序
- 2024-12-26 08:43:00
- admin 原创
- 106
问题描述:
代码:
d = {'a': 0, 'b': 1, 'c': 2}
l = d.keys()
print l
这将打印['a', 'c', 'b']
。我不确定该方法如何keys()
确定 中的关键字顺序l
。但是,我希望能够以“正确”的顺序检索关键字。
当然,正确的顺序将创建列表['a', 'b', 'c']
。
解决方案 1:
Python 3.7+
在 Python 3.7.0dict
中,对象的插入顺序保存特性已被声明为 Python 语言规范的正式组成部分。因此,您可以依赖它。
Python 3.6(CPython)
从 Python 3.6 开始,对于 Python 的 CPython 实现,字典默认保持插入顺序。但这被视为实现细节;collections.OrderedDict
如果您希望在其他 Python 实现中保证插入顺序,您仍应使用。
Python >=2.7 且 <3.6
collections.OrderedDict
当您需要dict
记住插入项目的顺序时,请使用该类。
解决方案 2:
您可以使用OrderedDict(需要Python 2.7)或更高版本。
另请注意,由于您创建的已经忘记了元素的顺序,OrderedDict({'a': 1, 'b':2, 'c':3})
因此 不起作用。相反,您需要使用。dict
`{...}`OrderedDict([('a', 1), ('b', 2), ('c', 3)])
正如文档中提到的,对于低于 Python 2.7 的版本,您可以使用此配方。
解决方案 3:
>>> print sorted(d.keys())
['a', 'b', 'c']
使用sorted 函数,对传入的可迭代对象进行排序。
该.keys()
方法以任意顺序返回键。
解决方案 4:
来自http://docs.python.org/tutorial/datastructures.html:
“字典对象的 keys() 方法返回字典中使用的所有键的列表,按任意顺序排列(如果希望对其进行排序,只需对其应用 sorted() 函数)。”
解决方案 5:
当您需要使用时,只需对列表进行排序即可。
l = sorted(d.keys())
解决方案 6:
虽然顺序并不重要,因为字典是哈希表。它取决于推入的顺序:
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'])