We access dictionaries through their keys. If we don’t care the order, then just use the in
operator in a for
loop. Previous to Python 3.6 dictionaries did not remember the order of insertion and iteration order was somewhat random. Post Python 3.6 dictionaries do retain insertion order (not to be confused with alphabetical).
for key in object:
print ("{key}: {value}".format(key=key, value=object[key])
If we want the keys alphabetical,
for key in sorted(object):
print ("{key}: {value}".format(key=key, value=object[key])
or,
for key in sorted(object.keys()):
print ("{key}: {value}".format(key=key, value=object[key])
Now let’s see if it works. First we’ll create some raw data.
>>> raw_data = "a quick brown fox jumps over the lazy dog".split()
>>> raw_data += "the rain in Spain falls mainly in the plains".split()
>>> raw_data += "a bird in the hand is worth two in the bush".split()
>>> raw_data += "many a comet falls into the sun".split()
Every word in the strings above is a list element. Their order is preserved but we don’t really care about that. Good to know, though.
We wish to make this into a dictionary of words and their word count, known as a histogram. To set this up we’ll buzz through the list and create a dictionary of keys, giving them a value of zero.
>>> raw_dict = {k: 0 for k in raw_data}
Now we can buzz through the list once more and add to the count of each word (key) in the dictionary.
>>> for k in raw_data:
raw_dict[k] += 1
We now have a dictionary full of keys (the words in the list) and a count of their occurrences. Fun time ahead as we sort through this to construct a histogram.
>>> histo = sorted(((v, k) for k, v in raw_dict.items()), reverse=True)
>>>
And now we get to express our dictionary in order of keyword occurrence…
>>> for x in histo:
v, k = x
print ("{key}: {value}".format(key=k, value=v))
the: 6
in: 4
a: 3
falls: 2
worth: 1
two: 1
sun: 1
rain: 1
quick: 1
plains: 1
over: 1
many: 1
mainly: 1
lazy: 1
jumps: 1
is: 1
into: 1
hand: 1
fox: 1
dog: 1
comet: 1
bush: 1
brown: 1
bird: 1
Spain: 1
>>>