-4

I have a question about the order of the dictionary in python. I am in python 2.7

array ={"dad":"nse","cat":"error","bob":"das","nurse":"hello"}

for key in array:
    print key

why result shows

dad
bob
nurse
cat

NOT

dad 
cat
bob
nurse
Erik Godard
  • 5,930
  • 6
  • 30
  • 33
fallor
  • 1
  • there is no order in dicts – njzk2 Jul 21 '16 at 21:49
  • Please look into documentation: https://docs.python.org/3/tutorial/datastructures.html#dictionaries – avtomaton Jul 21 '16 at 21:55
  • 4
    Possible duplicate of [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) – cdarke Jul 21 '16 at 21:56

3 Answers3

1

In the standard Python implementation, CPython, dictionaries have no guaranteed order, per the docs.

kindall
  • 178,883
  • 35
  • 278
  • 309
0

According to the Python documentation, there is no ordering to the elements in a dictionary. Python can return the entries to you in whatever order it chooses. If you want a dictionary with order, you can use an OrderedDict. However, since it must maintain order, this collection has worse performance than a normal Dict.

Erik Godard
  • 5,930
  • 6
  • 30
  • 33
0

Yes, I agree, dictionary is an independent data structure, which means it always live its life :) , but check out this example:

from collections import OrderedDict
days = {"Monday": 1, "Tuesday": 2, "Wednesday": 3, "Thursday": 4, "Friday": 5}
print days
sorted_days = OrderedDict(sorted(days.items(), key=lambda t: t[1]))
print sorted_days
print list(days)[0]
print list(sorted_days)[0]

With output:

{'Friday': 5, 'Tuesday': 2, 'Thursday': 4, 'Wednesday': 3, 'Monday': 1}
OrderedDict([('Monday', 1), ('Tuesday', 2), ('Wednesday', 3), ('Thursday', 4), ('Friday', 5)])
Friday
Monday

In lambda expression t[1] indicates: according to what, the dictionary will be sorted. So I think it might solve the problem.

But.. couldn't find a strict answer why dictionary has such order when printed. I suppose it's a matter of memory, where the dictionary arranges itself.

Jagoda Gorus
  • 329
  • 4
  • 18