Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Merge Dictionaries

Python Merge Dictionaries

Document Object Reference Manual Python3 Examples

Given two dictionaries, then merge them into one dictionary.

Example 1: Using the update() method, the second argument is merged into the first

def

Merge

(

dict1

,

dict2

)

:

return

(

dict2

.

update

(

dict1

)

)

Two dictionaries

dict1

= {

'

a

'

:

10

,

'

b

'

:

8

}

dict2

= {

'

d

'

:

6

,

'

c

'

:

4

}

Returns None

print

(

Merge

(

dict1

,

dict2

)

)

dict2 has merged dict1

print

(

dict2

)

The output of the code above is:


None
{'d': 6, 'c': 4, 'a': 10, 'b': 8}

Example 2: Using **, the function imports arguments as a dictionary

def

Merge

(

dict1

,

dict2

)

:

res

= {**

dict1

, **

dict2

}

return

res

Two dictionaries

dict1

= {

'

a

'

:

10

,

'

b

'

:

8

}

dict2

= {

'

d

'

:

6

,

'

c

'

:

4

}

dict3

=

Merge

(

dict1

,

dict2

)

print

(

dict3

)

The output of the code above is:


{'a': 10, 'b': 8, 'd': 6, 'c': 4}

Document Object Reference Manual Python3 Examples