z82n
z82n

Reputation: 113

In what order are keys inserted into a dictionary?

>>> stuff = {'age': 23, 'name': 'ZaneTribal', 'height': 74}
>>> print stuff
{'age': 23, 'name': 'ZaneTribal', 'height': 74}
>>> stuff['born in'] = 'Montreal'
>>> print stuff
{'age': 23, 'born in': 'Montreal', 'name': 'ZaneTribal', 'height': 74}
>>> stuff['children'] = 'Nope'
>>> stuff
{'age': 23, 'born in': 'Montreal', 'children': 'Nope', 'name': 'ZaneTribal', 'height': 74}
>>> stuff['zoo'] = 'WTF'
>>> stuff
{'name': 'ZaneTribal', 'age': 23, 'zoo': 'WTF', 'born in': 'Montreal', 'height': 74, 'children': 'Nope'}

When adding to dicts, how does Python decide where to place new keys? The order is clearly not alphabetical, nor by type.

Upvotes: 0

Views: 55

Answers (3)

Jason Hu
Jason Hu

Reputation: 6333

dict in python is actually hash table.

therefore, it's meaningless to track where python put the keys, since things after hashed should be considered random.

when you use keys() to extract every key, you should not make any assumption about order too.

Upvotes: 1

cdhowie
cdhowie

Reputation: 169413

The order is undefined. Python can put the keys in whatever order it wants, and this order can change between Python versions. You should not rely on the order of dict keys.

Upvotes: 2

kindall
kindall

Reputation: 184405

Dictionaries are unordered. The order they come out in when you print them depends on internal details of the implementation.

If you need to retain order, use collections.OrderedDict.

Upvotes: 3

Related Questions