How to join several dictionaries in Python?

5

In some languages, you can join objetos/array to one.

For example, in PHP, I can join multiple arrays like this:

$userInfo = ['name' => 'Wallace']
$jobInfo = ['job' => 'Developer']
$ageInfo = ['age' => '26']

$info = array_merge($userInfo, $jobInfo, $ageInfo)

This would return:

['name' => 'Wallace', 'job' => 'Developer', 'age' => '26']

What about Python? How do I?

If I have the following dictionaries, how can I merge them into one?

a = {"A" : 1}
b = {"B" : 2}
c = {"C": 3}

Note : I thought about using for already, but I asked the question to find a simpler solution than that.     

asked by anonymous 16.11.2016 / 13:03

3 answers

7

As demonstrated in this response from SOen , you can use

z = {}
z.update(a)
z.update(b)
z.update(c)

Or something like:

def merge_dicts(*dict_args):
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result

merge_dicts(a, b, c)

As of 3.5 ( PEP 448 ) this has been proposed

z = {**a, **b}
    
16.11.2016 / 13:12
3

You can use update , then we have:

a = {"A" : 1}
b = {"B" : 2}
c = {"C": 3}
abc = {}

abc.update(a)
abc.update(b)
abc.update(c)
print(abc) # {'A': 1, 'B': 2, 'C': 3}

Since the dictionaries are not contained in the same collection (list, tuple etc ...), I think the best way is this

    
16.11.2016 / 13:12
3

You can use the update method to update a certain existing dictionary or create a new one and update it.

>>> a = {"A" : 1}
>>> b = {"B" : 2}
>>> c = {"C": 3}
>>> c.update(a)
>>> c.update(b)
>>> c
{'A': 1, 'C': 3, 'B': 2}

Using a new dictionary:

>>> novo = {}
>>> novo.update(a)
>>> novo.update(b)
>>> novo.update(c)
>>> novo
{'A': 1, 'C': 3, 'B': 2}
    
16.11.2016 / 13:13