Reputation: 113
>>> 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
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
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
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