据我所知,在Python(3)中,字典本质上是无序的,并且循环它们(例如打印出键)将导致基本上任意排序的输出,这可能在每次执行代码之间发生变化。然而,我所看到的一个我正在研究的例子似乎与此相矛盾 - 在这个特定问题上循环一个字典我正在处理(下面)总是导致有序输出。如果有人可以了解我的误解在哪里,我将不胜感激。谢谢:))
word_list = ["hi", "green", "banana", "apple", "her"]
length_dictionary = {}
for word in word_list:
length = len(word)
if length in length_dictionary:
length_dictionary[length] += [word]
else:
length_dictionary[length] = [word]
for length in length_dictionary:
print(length, "letter words:")
for word in length_dictionary[length]:
print(word, end=" ")
print("\n")
输出:
2 letter words:
hi
3 letter words:
her
5 letter words:
green apple
6 letter words:
banana