DCaugs DCaugs - 3 months ago 9
Python Question

Random order of returned values in python dictionary

I don't understand this and it's going to bother me until I do.

This python code counts the number of times each character appears in the 'message' variable:

message = 'Some random string of words'

dictionary= {}

for character in message.upper():
dictionary.setdefault(character,0)
dictionary[character] = dictionary[character] + 1

print(dictionary)


If you run this multiple times, you will notice the counts are returned in seemingly random order each time. Why is this? I would think that the loop should start at the beginning of the character string each time and return the values in a consistent order...but they don't. Is there some element of randomness in the
setdefault()
,
print()
, or
upper()
methods that impacts the order of processing of the string?

Answer

Because of two things:

  • Dictionaries "aren't ordered". You of course get some order, but it depends, among other things, on the hash values of the keys.
  • You use (single-character) strings as keys, and string hashes are randomized. If you do print(hash(message)) or even just print(hash('c')) then you'll see that that differs from one run to the next as well.

So since the order depends on the hashes and the hashes change from one run to the next, of course you can get different orders.

On the other hand, if you repeat it in the same run, you'll likely get the same order:

message = 'Some random string of words'
for _ in range(10):
    dictionary= {}
    for character in message:
        dictionary.setdefault(character,0)
        dictionary[character] = dictionary[character] + 1
    print(dictionary)

I just ran that and it printed the exact same order all ten times, as expected. Then I ran it again, and it printed a different order, but again all ten times the same. As expected.

Comments