Parmy
Parmy

Reputation: 61

What dictates the order of data in a dictionary in Python?

What determines the order of items in a dictionary(specifically in Python, though this may apply to other languages)? For example:

>>> spam = {'what':4, 'shibby':'cream', 'party':'rock'}
>>> spam
{'party': 'rock', 'what': 4, 'shibby': 'cream'}

If I call on spam again, the items will still be in that same order. But how is this order decided?

Upvotes: 3

Views: 99

Answers (3)

Velimir Mlaker
Velimir Mlaker

Reputation: 10985

Because dictionary keys are stored in a hash table. According to http://en.wikipedia.org/wiki/Hash_table:

The entries stored in a hash table can be enumerated efficiently (at constant cost per entry), but only in some pseudo-random order.

Upvotes: 0

torek
torek

Reputation: 489888

The order in an ordinary dictionary is based on an internal hash value, so you're not supposed to make any assumptions about it.

Use collections.OrderedDict for a dictionary whose order you control.

Upvotes: 1

user1786283
user1786283

Reputation:

According to python docs,

Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.

They are arbitary, again from docs:

A dictionary’s keys are almost arbitrary values. Values that are not hashable, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)

Upvotes: 1

Related Questions