Home > Article > Backend Development > 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
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 dictionaries in Python ordered?. For more information, please follow other related articles on the PHP Chinese website!