Printing contents of dictionary in random order

匆匆过客 提交于 2019-12-13 04:58:51

问题


I am fairly new to Python. Infact, today is my first day in Python. I was following a tutorial and read about dictionary.

But I don't know what is the order in which contents of a dictionary are displayed.

Below is my code:

dir = {'Z':1,'Y':3,'X':5,'V':7,'U':9,'T':2,'S':4,'R':6,'Q':8,'P':10};
print dir;

and following is the Output:

{'Q': 8, 'P': 10, 'S': 4, 'R': 6, 'U': 9, 'T': 2, 'V': 7, 'Y': 3, 'X': 5, 'Z': 1}

Can anybody explain how I get this output and not the list in its original sequence.

P.S: Sorry for a lame question :(


回答1:


From the Python Docs (They will be your friend while using Python)

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

which means that they are stored in no fixed order and hence printed out in no fixed order! Since, the dictionaries are likely implemented using hash tables, there is no 'order' that they follow.

If you want an ordered dictionary, collections.OrderedDict() might be useful.




回答2:


If your read the python documentation about dictionnaries http://docs.python.org/2/tutorial/datastructures.html#dictionaries

you will see that it's normal. If you want it to be ordered you must do some sort operation, otherwise it's an arbitrary order.

I hope it helps.



来源:https://stackoverflow.com/questions/16585859/printing-contents-of-dictionary-in-random-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!