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?