1

I need help merging two dictionaries. I can merge them but the problem is I need the two dictionaries to maintain their order.

For expample:

x = {'a':1, 'b': 2}
y = {'b':10, 'c': 11}
z = dict(x.items() + y.items())
print z 

{'a': 1, 'c': 11, 'b': 10}

This output is a problem. I need the output to be: {'a':1, 'b':10, 'c': 11} The order of the letters must be maintained.

tashuhka
  • 5,028
  • 4
  • 45
  • 64
user2943615
  • 113
  • 3
  • 7

1 Answers1

4

The base Python dictionary class is unordered. You'll need to use collections.OrderedDict instead, if you're on 2.7 or 3.anything, or one of the many implementations you can find easily with Google for 2.6 or earlier. Here's one recipe that the Python docs link to for 2.4-2.6: http://code.activestate.com/recipes/576693/

Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • so i would have to do "import collections" then x = collections.OrderedDict{'a':1, 'b':2} ? – user2943615 Nov 01 '13 at 02:32
  • 1
    If you want to control the order, you have to give the `OrderedDict` an iterable of key/value pairs, or add them after creating it. Something like: `x = collections.OrderedDict([('a', 1), ('b', 2)])`. Or `x = collections.OrderedDict(); x['a'] = 1; x['b'] = 2`. – Peter DeGlopper Nov 01 '13 at 02:35