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

Max*_*Max 1 python sorting dictionary key

因为我想将一个字典解码为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)
Run Code Online (Sandbox Code Playgroud)

out put是

{'a': '1st', 'ab': '2nd'}
{'b': '1st', 'bc': '2nd'}
{'c': '1st', 'cd': '2nd'}
{'de': '2nd', 'd': '1st'}
{'ef': '2nd', 'e': '1st'}
{'fg': '2nd', 'f': '1st'}
Run Code Online (Sandbox Code Playgroud)

因为ascii中d是100?

怎么解释呢?我能改变它的命令吗?

Ble*_*der 5

字典不是用Python排序的.如果您想要排序的词典,请使用OrderedDict:

>>> from collections import OrderedDict
>>> a = OrderedDict((('f','1st'),('fg','2nd')))
>>> a
OrderedDict([('f', '1st'), ('fg', '2nd')])
Run Code Online (Sandbox Code Playgroud)

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