The order of keys in dictionaries

前端 未结 6 966
渐次进展
渐次进展 2020-11-22 14:32

Code:

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

print l

This prints [\'a\', \'c\', \'b\']. I\'m unsure of how the metho

6条回答
  •  执笔经年
    2020-11-22 14:44

    Python 3.7+

    In Python 3.7.0 the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.

    Python 3.6 (CPython)

    As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict if you want insertion ordering that's guaranteed across other implementations of Python.

    Python >=2.7 and <3.6

    Use the collections.OrderedDict class when you need a dict that remembers the order of items inserted.

提交回复
热议问题