Skip to main content
 首页 » 编程设计

python之python dict 的键默认排序发生了什么

2025年05月04日19开发

因为我想把一个dict解码成json,但是我发现输出顺序不是我想要的,然后我做了这样的测试:

a = {'a':'1st','ab':'2nd'} 
print(a) 
a = {'b':'1st','bc':'2nd'} 
print(a) 
a = {'c':'1st','cd':'2nd'} 
print(a) 
a = {'d':'1st','de':'2nd'} 
print(a) 
a = {'e':'1st','ef':'2nd'} 
print(a) 
a = {'f':'1st','fg':'2nd'} 
print(a) 

输出是

{'a': '1st', 'ab': '2nd'} 
{'b': '1st', 'bc': '2nd'} 
{'c': '1st', 'cd': '2nd'} 
{'de': '2nd', 'd': '1st'} 
{'ef': '2nd', 'e': '1st'} 
{'fg': '2nd', 'f': '1st'} 

因为 d 在 ascii 中是 100?

如何解释?我可以更改iter顺序吗?

请您参考如下方法:

字典在 Python 中不排序。如果你想要排序的字典,使用 OrderedDict:

>>> from collections import OrderedDict 
>>> a = OrderedDict((('f','1st'),('fg','2nd'))) 
>>> a 
OrderedDict([('f', '1st'), ('fg', '2nd')]) 

但是,为了构造一个 OrderedDict,您需要使用一个保留其排序顺序的对象,例如 list 或 tuple.