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
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
In the standard Python implementation, CPython, dictionaries have no guaranteed order, per the docs.
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.
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.