1

I am creating a module in which a dictionary is used. This dictionary contains some key/value pairs, whose order must be preserved when using in other modules. But whenever I iterate over dictionary and print the keys, the keys are not in the order in which they key/value pairs are inserted.

So my question is how should I preserve the order of key/value pair in a dictionary?

Any help will be highly appreciated...

Thanx in advance...

Uday0119
  • 770
  • 1
  • 7
  • 23
  • 2
    Do you mean the order in which the items were added to the dictionary? In that case you can use `OrderedDict` from `collections`: http://docs.python.org/dev/library/collections.html#collections.OrderedDict – Simeon Visser Mar 18 '12 at 12:44
  • @SimeonVisser: Yes, exactly. I want to maintain the order in which items are inserted. Thanks for the link. I'll check it and revert back to you... – Uday0119 Mar 18 '12 at 12:48
  • 1
    I see there is a package at PyPI that provides OrderedDict functionality for Python 2.4, 2.5, and 2.6: http://pypi.python.org/pypi/ordereddict . You can give that a try. – Simeon Visser Mar 18 '12 at 12:57
  • 1
    @SimeonVisser: I've checked python 2.7 documentation, and I found that OrderedDict exist for python 2.7... Thanx for the help... :) – Uday0119 Mar 18 '12 at 13:13

1 Answers1

-1

We know that regular Python dictionaries iterate over pairs in an arbitrary order, hence they do not preserve the insertion order of pairs. Python 2.7. introduced a new “OrderDict” class in the “collections” module and it provides the same interface like the general dictionaries but it traverse through keys and values in an ordered manner depending on when a key was first inserted. Eg:

from collections import OrderedDict
d = OrderDict([('Company-id':1),('Company-Name':'Intellipaat')])
d.items() # displays the output as: [('Company-id':1),('Company-Name':'Intellipaat')]
Alon Eitan
  • 11,997
  • 8
  • 49
  • 58