2

If I have two dictionaries I'd like to combine in Python, i.e.

a = {'1': 1, '2': 2}
b = {'3': 3, '4': 4}

If I run update on them it reorders the list:

a.update(b)
{'1': 1, '3': 3, '2': 2, '4': 4}

when what I really want is attach "b" to the end of "a":

{'1': 1, '2': 2, '3': 3, '4': 4}

Is there an easy way to attach "b" to the end of "a" without having to manually combine them like so:

for key in b:
    a[key]=b[key]

Something like += or append() would be ideal, but of course neither works on dictionaries.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
digitaldreamer
  • 52,552
  • 5
  • 33
  • 28
  • 2
    The `update()` method is the correct way to "combine" dictionaries, so perhaps you need to explain why you want what you think you want... Do you actually have a reason to want a dictionary with a particular order, or were you just getting confused by the behaviour you saw, but the combined dictionary does actually suit you as-is? – Peter Hansen Apr 06 '10 at 16:05
  • It make a lot of sense now. I was thinking that dictionaries had an order, which others have mentioned is not correct. – digitaldreamer Apr 06 '10 at 16:12
  • If order is important to you, you might consider a list of tuples instead of a dictionary. Otherwise, as others mentioned, there's always OrderedDictionary. – jemfinch Apr 06 '10 at 20:52

5 Answers5

11

A python dictionary has no ordering -- if in practice items appear in a particular order, that's purely a side-effect of the particular implementation and shouldn't be relied on.

Andrew Aylett
  • 39,182
  • 5
  • 68
  • 95
2

Dictionaries are unordered: they do not have a beginning or an end. Whether you use update or the for loop, the end result will still be unordered.

If you need ordering, use a list of tuples instead. Python 3.1 has an OrderedDict type which will also be in Python 2.7.

interjay
  • 107,303
  • 21
  • 270
  • 254
2

Dictionaries are not ordered. If you need ordering, you might try something like a list.

WhirlWind
  • 13,974
  • 3
  • 42
  • 42
1

There is an ordered dictionary in the standard library as of Python 3.1.1, but the use-cases for it are limited. Typically if you are using a dictionary, you are simply interested in the mapping of keys to values, and not order. There are various recipes out there for ordered dictionaries as well if you aren't using Python 3.x but you should really first ask yourself if order is important and if so, whether or not you are using the right data structure.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
0

I think you're misunderstanding the use of dictionaries. You do not access them sequence or location. You access them from the keys, which in your case also happen to be numbers. They are hash tables and are supposed to work like this. You're doing it correctly.

Vetsin
  • 2,245
  • 1
  • 20
  • 24