简体   繁体   English

以随机顺序打印字典内容

[英]Printing contents of dictionary in random order

I am fairly new to Python. 我对Python相当陌生。 Infact, today is my first day in Python. 实际上,今天是我使用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} {'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. 谁能解释我如何获得此输出,而不是原始顺序的列表。

PS: Sorry for a lame question :( PS:对不起,一个for脚的问题:(

From the Python Docs (They will be your friend while using Python) 来自Python文档 (使用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. 如果需要有序字典,则collections.OrderedDict()可能会有用。

If your read the python documentation about dictionnaries http://docs.python.org/2/tutorial/datastructures.html#dictionaries 如果您阅读了有关字典的python文档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. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM