在循环Python中自动进行字典排序

2024-04-25 10:01:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用python写下了这个程序

创建字典

 a = { 'a':'b', 'x':'x', '2':'2' }

运行后循环

 for c in a:
   a[c]

结果是

'2'
'b'
'x'

我想,应该有“b x 2”的结果,但它会自动排序,为什么会发生这种情况,我如何控制这种情况


Tags: in程序for字典排序情况
1条回答
网友
1楼 · 发布于 2024-04-25 10:01:01

python中的Dictionary没有顺序,您接收密钥的顺序基本上取决于python实现。您的代码不应该依赖于它

documentation-

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)


如果顺序对程序很重要,请使用^{}。示例-

>>> from collections import OrderedDict
>>> d = OrderedDict([('a','b'),('x','x'),('2','2')])
>>> for c in d:
...     d[c]
...
'b'
'x'
'2'

相关问题 更多 >