Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append a dictionary to a dictionary [duplicate]

I have two existing dictionaries, and I wish to 'append' one of them to the other. By that I mean that the key,values of the other dictionary should be made into the first dictionary. For example:

orig = {    'A': 1,    'B': 2,    'C': 3, }  extra = {    'D': 4,    'E': 5, }  dest = # Something here involving orig and extra  print dest {    'A': 1,    'B': 2,    'C': 3,    'D': 4,    'E': 5 } 

I think this all can be achieved through a for loop (maybe?), but is there some method of dictionaries or any other module that saves this job for me? The actual dictionaries I'm using are really big...

like image 672
Javier Novoa C. Avatar asked Jan 19 '12 17:01

Javier Novoa C.


People also ask

Can you append a dictionary to a dictionary?

Use the update() Method to Add a Dictionary to Another Dictionary in Python. The update() method concatenates one dictionary to another dictionary. Using this method, we can insert key-value pairs of one dictionary to the other dictionary.

Can you have duplicates in a dictionary?

[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.

Can we insert duplicate keys into a dictionary?

It is not possible. All keys should be unique.

Can a Python dictionary have duplicate keys?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.


2 Answers

You can do

orig.update(extra) 

or, if you don't want orig to be modified, make a copy first:

dest = dict(orig)  # or orig.copy() dest.update(extra) 

Note that if extra and orig have overlapping keys, the final value will be taken from extra. For example,

>>> d1 = {1: 1, 2: 2} >>> d2 = {2: 'ha!', 3: 3} >>> d1.update(d2) >>> d1 {1: 1, 2: 'ha!', 3: 3} 
like image 95
mipadi Avatar answered Oct 15 '22 01:10

mipadi


There are two ways to add one dictionary to another.

Update (modifies orig in place)

orig.update(extra)    # Python 2.7+ orig |= extra         # Python 3.9+ 

Merge (creates a new dictionary)

# Python 2.7+ dest = collections.ChainMap(orig, extra) dest = {k: v for d in (orig, extra) for (k, v) in d.items()}  # Python 3 dest = {**orig, **extra}           dest = {**orig, 'D': 4, 'E': 5}  # Python 3.9+  dest = orig | extra 

Note that these operations are noncommutative. In all cases, the latter is the winner. E.g.

orig  = {'A': 1, 'B': 2} extra = {'A': 3, 'C': 3}  dest = orig | extra # dest = {'A': 3, 'B': 2, 'C': 3}  dest = extra | orig # dest = {'A': 1, 'B': 2, 'C': 3} 

It is also important to note that only from Python 3.7 (and CPython 3.6) dicts are ordered. So, in previous versions, the order of the items in the dictionary may vary.

like image 32
Nuno André Avatar answered Oct 14 '22 23:10

Nuno André