0

How does python accesses the entries of a dictionary when using a for loop? I think that theoretically it is random but when I tried it using integers as keys I saw that it was accessing the dictionary in ascending order of the keys.

For example I tried:

 x = { 
     1: 5,
     3: 2,
     2: 15 
 }

for n in x:
    print n

and I got:

1,2,3

as an output.

I got the same answer when I used letters as the key values

x = { 
     d: 5,
     o: 2,
     c: 15 
 }

for n in x:
    print n

and I got:

c,d,o

Is that always the case??

m_papas
  • 91
  • 1
  • 12
  • 2
    No, you cannot rely on the ordering of _dict_. If order is matters to you, then use an [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. – John1024 Oct 30 '15 at 04:59
  • dictionaries has no sense of order, as john pointed, if you need a sense of order, use orderedDict instead of normal dicts. – levi Oct 30 '15 at 05:01
  • Thank you. I don't really want to solve something. I was just curious on what is the criterion that python uses to access the entries of a dictionary – m_papas Oct 30 '15 at 05:05

0 Answers0