-2

I have a dictionary that I keep updating buy using .update to add a new value and key, adding new keys as it goes through a loop. I want the dictionary to print out the values in the order that I add them. Is that possible?

Kate
  • 53
  • 1
  • 1
  • 8
  • 2
    The standard dictionary does not take the order in account. Use [OrderedDict](https://docs.python.org/2/library/collections.html#collections.OrderedDict) instead. Btw, this has been discussed several times here on SO: [1](http://stackoverflow.com/questions/25480089/initializing-an-ordereddict-using-its-constructor), [2](http://stackoverflow.com/questions/15711755/converting-dict-to-ordereddict), [3](http://stackoverflow.com/questions/15733558/python-ordereddict-not-keeping-element-order), [4](http://stackoverflow.com/questions/719744/what-is-the-best-ordered-dict-implementation-in-python), ... – HelloWorld Sep 28 '15 at 18:33

2 Answers2

4

You need to use an OrderedDict rather than a standard dictionary. It will maintain the order, but otherwise acts like a normal dict.

Chad S.
  • 6,252
  • 15
  • 25
0

To do that, you can use an OrderedDict as it remembers the order in which its contents are added. Its a subclass of normal Python dictionary so will have access to all the functions of a dictionary.

Example:

In [1]: import collections

In [2]: normal_dict = {}

In [3]: normal_dict['key1'] = 1 # insert key1

In [4]: normal_dict['key2'] = 2 # insert key2

In [5]: normal_dict['key3'] = 3 # insert key3

In [6]: for k,v in normal_dict.items(): # print the dictionary
   ...:     print k,v
   ...:     
key3 3 # order of insertion is not maintained
key2 2
key1 1

In [7]: ordered_dict = collections.OrderedDict()

In [8]: ordered_dict['key1'] = 1 # insert key1

In [9]: ordered_dict['key2'] = 2 # insert key2

In [10]: ordered_dict['key3'] = 3 # insert key3

In [11]: for k,v in ordered_dict.items(): # print the dictionary
             print k,v
   ....:     
key1 1 # order of insertion is maintained
key2 2
key3 3
Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126