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...
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.
[C#] Dictionary with duplicate keysThe Key value of a Dictionary is unique and doesn't let you add a duplicate key entry.
It is not possible. All keys should be unique.
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
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}
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)
dict
s are ordered. So, in previous versions, the order of the items in the dictionary may vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With