Merge two dictionaries Python

Last Updated On Thursday 20th Jan 2022

Python Merge Dictionaries

  • Dictionaries are Python’s implementation of a data structure that is more generally known as an associative array.
  • A dictionary consists of a collection of key-value pairs.
  • Each key-value pair maps the key to its associated value.

Python Dictionary update()

The update() method updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.

Syntax

	dict.update([other])
	

Python Join Dictionaries

	students = { 'Adam': 11, 'Alice': 12 }
newStudent = { 'Benny':13 }

students.update(newStudent)

print(students)
	

Python unPacking operator

We can merge dictionaries in one line by simply using the unpacking operator (**).

Syntax

	{**dict1, **dict2, **dict3}
	

Add Two Dictionaries Python

	students = { 'Adam': 11, 'Alice': 12 }
newStudent = { 'Benny':13 }

print({**students, **newStudent})
	

Python collections.ChainMap

	from collections import ChainMap

students = { 'Adam': 11, 'Alice': 12 }
newStudent = { 'Benny':13 }

all = ChainMap(students,newStudent)

print(all)
# ChainMap({'Adam': 11, 'Alice': 12}, {'Benny': 13})
	

We can, still, use this object as we would use any other dictionary. like below,

	print(all['Adam'])
# 11
	

Python Combine Dictionaries

  • The dict() function creates a dictionary.
  • The list() function creates a list object.
  • A list object is a collection which is ordered and changeable.
	students = { 'Adam': 11, 'Alice': 12 }
newStudent = { 'Benny':13 }

print(dict(list(students.items()) + list(newStudent.items())))
	
	{'Adam': 11, 'Alice': 12, 'Benny': 13}
	

References