It was my understanding that in Python (3), dictionaries are inherently unordered and that looping over them (to print out the keys, for example) would result in an essentially arbitrarily ordered output which could change between each execution of the code. However what I'm seeing with an example I'm working on seems to contradict this - looping over a dictionary in this particular question I'm working on (below) always results in an ordered output. I would appreciate it if someone could shed some light on where my misunderstanding is. Thanks :)
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")
Output:
2 letter words:
hi
3 letter words:
her
5 letter words:
green apple
6 letter words:
banana