Home > Backend Development > Python Tutorial > Are dictionaries in Python ordered?

Are dictionaries in Python ordered?

silencement
Release: 2019-06-12 15:11:23
Original
9410 people have browsed it

Are dictionaries in Python ordered?

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
Copy after login

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
Copy after login

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
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template