4
my_dict = {'a':10, 'b':20, 'c':30}

for key in my_dict:
    print key, my_dict[key]

gives

a 10
c 30
b 20

and

my_dict = {'a':10, 'c':30, 'b':20}

for key in my_dict:
    print key, my_dict[key]

gives the same result

a 10
c 30
b 20

I was wondering why isn't the output like a 10 b 20 c 30. How is selection of keys done while iterating through a dictionary? Is it random?

prashanth
  • 4,197
  • 4
  • 25
  • 42
  • This is because dictionary are not ordered – styvane Dec 16 '15 at 07:21
  • @user3100115 Ok. But is there any logic to that why it is like that. I mean if we iterate in a list, it will go in a particular order. Why not the same behavior in dictionary..just curious.. – prashanth Dec 16 '15 at 07:28
  • 2
    [Why is the order in Python dictionaries and sets arbitrary?](http://stackoverflow.com/questions/15479928/why-is-the-order-in-python-dictionaries-and-sets-arbitrary) – styvane Dec 16 '15 at 07:32

4 Answers4

2

The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it). To check whether a single key is in the dictionary, use the in keyword.

The order of keys in a dict() is not defined (it depends on which implementation of Python you're using). In order to iterate through dict in an ordered fashion:

my_dict = {'a': 10, 'b': 20, 'c': 30}
for key in sorted(my_dict.keys()):
    print key, my_dict[key]

This will give you the right order:

a 10
b 20
c 30

The reason why keys are not sorted is that dict() uses hash table to store them, that is also why you can only have one unique key and why you can have composite keys that are composed of hashable objects. The keys are sorted by their hash, for a more in-depth explanation see this SO question

Community
  • 1
  • 1
mirosval
  • 6,671
  • 3
  • 32
  • 46
2

Dictionary keys are sorted by their hash, So you can't expect any order there.

If you need order keys you should use SortedDict.

If you need to preserve key order, you should use OrderedDict

Ali Nikneshan
  • 3,500
  • 27
  • 39
1

Python dictionary does not have an order. You need to sort keys if you want to iterate them in specific order.

For example to iterate keys lexicographic order using sorted:

>>> my_dict = {'a':10, 'c':30, 'b':20}
>>> for key in sorted(my_dict):
...     print key, my_dict[key]
... 
a 10
b 20
c 30
falsetru
  • 357,413
  • 63
  • 732
  • 636
0

If you want to specify an order, you can sort the keys as follows:

for key in sorted(my_dict.keys()):
    print '{0} {1}'.format(key, my_dict.get(key))

This produces:

a 10
b 20
c 30
hd1
  • 33,938
  • 5
  • 80
  • 91