How to join several Python dictionaries?

Asked

Viewed 2,721 times

5

In some languages, it is possible to unite objetos/array in one.

For example, in PHP, I can join several arrays thus:

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

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

That would return:

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

And in Python? How do I?

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

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

Note: I thought I’d use the for already, but I asked the question in order to find a simpler solution than that.

3 answers

8


As demonstrated in this response from Soen, can be used

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)

From the 3.5 onwards (PEP 448) this has been proposed

z = {**a, **b}
  • 1

    And I’m racking my brain trying to do this in Python 2.7. I’m glad you told me it’s from 3.5..

4

You can use the method update to update a particular 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}

3

You can use the 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 dictionaries are not contained in the same collection (list, tuple etc...), I think the best way is so

Browser other questions tagged

You are not signed in. Login or sign up in order to post.