Tutorial :Is there an easy way to “append()” two dictionaries together in Python?



Question:

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.


Solution:1

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.


Solution: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.


Solution:3

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


Solution:4

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.


Solution:5

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »