I wanted to clarify some points about dictionaries in Python, which may help some other Python enthusiasts in the future.
Let's start with a simple dictionary.
foo = {'a_2': 4, 'b_2': 5, 'a_1': 2, 'b_1': 1}
and displaying foo
gives,
In [31]: foo
Out[31]: {'a_1': 2, 'a_2': 4, 'b_1': 1, 'b_2': 5}
As one can see, foo
seems to be 'unordered'. However, upon reading further I've found that dictionaries are not inherently ordered, and the output when a dictionary is displayed is just based on the hash values of the keys.
My confusion arises when I loop over the dictionary using foo.iteritems()
or foo.items()
(both give the same result.)
for k, v in foo.iteritems():
print '{}: {}'.format(k, foo[k])
b_1: 1
b_2: 5
a_2: 4
a_1: 2
This output ordering does not agree with the order I entered the keys/values in foo
or the way they are outputted when foo
is called.
Does this have to do with how foo.iteritems()
generates its keys/values or something else?
I am using Python 2.7 on Ubuntu