1

I've run into a problem with looping through a dictionary. The following code:

d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
for k,v in d.iteritems():
    print k,v

Results in:

a 1
c 3
b 2

But the desired result is:

a 1
b 2
c 3

Does anyone know how to fix the loop somehow to preserve the order that the elements were assigned in? Thank you!

Charles
  • 947
  • 1
  • 15
  • 39

2 Answers2

2

In Python, normal dictionaries were designed to be unordered. Meaning, they should not be used here.

Instead, you should use a collections.OrderedDict:

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d['a'] = 1
>>> d['b'] = 2
>>> d['c'] = 3
>>> for k,v in d.iteritems():
...     print k,v
...
a 1
b 2
c 3
>>>

Unlike a normal dictionary, an OrderedDict is guaranteed to preserve the order in which the elements were assigned.

1

A dictionary does not preserve order, so you need to sort the keys:

for k,v in sorted(d.iteritems,key=lambda x: x[0]):
    print k,v

Alternatively, use a collections.OrderedDict object which internally maintains a list of keys in insertion order:

import collections
d = collections.OrderedDict()
...
for k,v in d.iteritems():
    print k,v
isedev
  • 18,848
  • 3
  • 60
  • 59