问题
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