【发布时间】:2021-12-23 09:43:08
【问题描述】:
我在对包含升序字符串和数字的文本文件中的字典进行排序时遇到问题。输出部分正确,但并非字典中的所有组件都以正确的顺序输出。
我正在使用的字典组装如下:
a 103,5
b 407,7
c 394,98
d 20,7
e 3,78
所以我的代码部分正确地打印了字典,但某些值的顺序仍然错误,例如:
e 3,78
d 20,7
c 394,98
a 103,5
b 407,7
这里,c 和 a 应该交换位置,因为 a 旁边的值小于 c 的值。这是一些代码:
a_dictionary = {}
file = open("example.txt")
for line in file:
value, key = line.split()
a_dictionary[value] = key
sort_file = sorted(a_dictionary.items(), key=lambda x: x[1])
for i in sort_file:
print(i[0], i[1])
【问题讨论】:
-
您为什么将字典的键命名为
value并将其值命名为key?这只是令人困惑!
标签: python sorting dictionary