Home  >  Article  >  Backend Development  >  Are python dictionaries in order?

Are python dictionaries in order?

silencement
silencementOriginal
2019-06-17 15:10:198412browse

Are python dictionaries in order?

The disorder of the dictionary means that the order in which data is stored in the dictionary is inconsistent with the order in which data is taken out of the dictionary.

The dictionary of Python2 is disordered

>>> d = {'a':-1,'b':-1,'c':-1}>>> d
{'a': -1, 'c': -1, 'b': -1}>>> for k,v in d.items():
...     print k,v
... 
a -1c -1b -1

So how to keep the dictionary in order? Using OrderedDict

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> d
OrderedDict([('a', 1), ('b', 2), ('c', 3)])
>>> for k,v in d.items():
...     print k,v
... 
a 1
b 2
c 3

Why is it unordered? The hash structure will have a head address, and the data inside will be scattered to different list chains, so it seems to be unordered. However, for the same set of dictionaries, there is always an identifier to connect, so when reading, it will also be stored as The data is taken in order, but not arranged according to specific rules.

Dictionaries in Python3 are ordered

>>> d = {'a':-1,'b':-1,'c':-1}
>>> d
{'a': -1, 'b': -1, 'c': -1}
>>> for k,v in d.items():
...     print(k,v)
... 
a -1
b -1
c -1

The above is the detailed content of Are python dictionaries in order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn