Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么';t Python3排序字典键?_Python 3.x_Dictionary - Fatal编程技术网

Python 3.x 为什么';t Python3排序字典键?

Python 3.x 为什么';t Python3排序字典键?,python-3.x,dictionary,Python 3.x,Dictionary,我有以下字典: dictionary = {'key5':10, 'key2':20} dictionary["key3"] = 21 dictionary["key1"] = 22 dictionary["key2"] = 23 sorted(dictionary.keys()) for key,value in dictionary.items(): print(key) 排序和打印后,值如下所示: key5 key1 key2 key3 为什么“key5”不是最后一个?so

我有以下字典:

dictionary = {'key5':10, 'key2':20}
dictionary["key3"] = 21
dictionary["key1"] = 22
dictionary["key2"] = 23

sorted(dictionary.keys())
for key,value in dictionary.items():
  print(key)
排序和打印后,值如下所示:

key5 
key1 
key2 
key3
为什么“key5”不是最后一个?

sorted()
返回排序后的序列。您需要迭代此序列才能获得排序结果。

这是因为
排序(dictionary.keys())
实际上,对于排序过的键,它不会修改集合本身,以便将键排序出来。从该链接(我的粗体):

从iterable中的项目返回一个新的排序列表

您正在调用
sorted
以获取已排序的键列表,但随后您基本上将其丢弃,并使用
dictionary.items()
返回未排序的集合

要按顺序处理密钥,您需要以下内容:

for key in sorted(dictionary.keys()):
    print(key)
这将根据需要打印出:

key1
key2
key3
key5