How to merge dictionaries in Python

Dictionary data type is used in python to store multiple values with keys. A new dictionary can be created by merging two or more dictionaries. Merging data is required when you need to combine same type of data that is stored in multiple dictionaries. For example, department wise employee data of any company is stored in many dictionaries. To generate a list of all employees of the company we will need to merge the data from these dictionaries. Many ways exist in Python for merging dictionaries. How you can merge dictionaries are shown in this article by using various examples.

Example-1: Merge two simple dictionaries

update() method is used in python to combine one dictionary with another dictionary. The following example shows the use of update() method. Here, two dictionaries are declared named stdDic1 and stdDic2. The values of stdDic1 will be added at the end of stdDic2. Next, for loop is used to print the keys and values of the merged dictionary.

# Define a dictionay of student list1
stdDic1 = {'Jony Lever':'English','Meena Ali':'CSE','John Micheal':'LAW'}

# Define a dictionary of student list2
stdDic2 = {'John Abraham':'CSE','Mily Hossain':'BBA','Ella Binte Nazir':'EEE'}

# Merge the second dictionary with the first dictionary
stdDic2.update(stdDic1)

# Print the keys and values of the merged dictionary
for val in stdDic2:
  print('\nName:',val)
  print('Department:',stdDic2[val])

Output:

Run the script. The following output will appear after running the script.

Example-2: Merge a simple dictionary and a list of multiple dictionaries

The following example shows how you can merge a dictionary with a list of multiple dictionaries. Here, a dictionary named isbn is declared to store the ISBN of the book as a key and book type as value. A list of dictionaries named book is declared to store book title and author name. zip() method is used to join the dictionaries or tuples and dict() method is used to create a dictionary. These methods are used in this script to create a new dictionary by merging isbn and book. Next, for loop is used to access the values of the merged dictionary.

# Declare a simple dictionary
isbn = {'67533344':'PHP','997544333':'Java','456688644':'VB.net'}

# Declare a list of multiple dictionary
book = [{'title': 'Murach PHP and MySQL', 'author': 'Joel Murach and Ray Harris'},
{'title': 'Java The Complete Reference', 'author': 'Herbert Schildt'},
{'title': 'Beginning VB.NET', 'author': 'Blair Richard, Matthew Reynolds, and
Thearon Willis'
}]

# Create a new dictionary by merging a single and multiple dictionary
mrgDict = dict(zip(isbn, book))

# Print the keys and values of the merged dictionary
for isbn in mrgDict:
  print('\nISBN:',isbn)
  print('Book Name:',mrgDict[isbn]['title'])
  print('Author Name:',mrgDict[isbn]['author'])

Output:

Run the script. The following output will appear after running the script.

Example-3: Merge two dictionaries using custom function

Two dictionaries can be merged by using copy() and update() methods in python. Here, the original values of the dictionary will be unchanged. mergeDic() function is defined to copy the values of the first dictionary in a variable named merged and add the values of the second dictionary in merged. Next, the values of the merged dictionary is printed.

# Declare two dictionaries
dict1 = { "name": "Abir", "age": 25, "gender": "Male" }
dict2 = { "profession": "Programmer", "email": "abir@gmail.com" }
''' Define a function to create a new dictionary merging both keys
    and values, of dict1 and dict2'''


def mergeDict(d1, d2):
  merged = d1.copy()
  merged.update(d2)
  return merged

# Call the function to merge
mrgDict = mergeDict(dict1,dict2)

# Print the values of merged dictionary
for idval in mrgDict:
  print(idval,':',mrgDict[idval])

Output:

Run the script. The following output will appear after running the script.

Example-4: Merging two dictionaries using (**) operator

Dictionaries can be merged without using a built-in or custom function by using a single expression. ‘**’operator is used in this example to merge two dictionaries. Here, two dictionary variables named dict1 and dict2 are declared, merged by using ‘**’ operator with the dictionary variables and stores the values into the variable, mrgDict.

# Declare two dictionaries
dict1 = { "Moniter": 500, "Mouse": 100, "Keyboard": 250 }
dict2 = { "HDD": 300, "Printer": 50, "Mouse":50 }

# Merge dictionaries using '**' operator
mrgDict = {**dict2, **dict1}

# Print the values of merged dictionary
for val in mrgDict:
  print(val,':',mrgDict[val])

Output:

Run the script. The following output will appear after running the script.

Example-5: Merging two dictionaries based on common keys

When two dictionaries contain the same key and if the value of the key is numeric then it may require to sum the values at the time of merging. This example shows how the numeric values of the same keys can be added when merging two dictionaries. Here, two dictionaries named store1 and store2 are declared. The keys and values of store1 are iterated through for loop and check which keys of store1 are equal to the keys of store2. If any key exists then the values of the key will be added.

# Declare two dictionaries
store1 = {'Pen': 150, 'Pencil': 250, 'Note Book': 100}
store2 = {'Eraser': 80, 'Pen': 50, 'Sharpner': 30, 'Pencil': 100}
 
# Merge the values of store2 with store1 with the common keys
for key in store1:
  if key in store2:
    store1[key] = store1[key] + store2[key]
  else:
    pass
 
# Print the keys and values of the merged dictionary
for val in store1:
  print(val,':',store1[val])

Output:

Run the script.  Here, two keys are common in the dictionaries. These are ‘Pen’ and ‘Pencil’ and the values of these keys are added.

Example-6: Merging all values of the dictionaries by counting common keys

In the previous example, the common values of two dictionaries are added based on a particular dictionary. This example shows how to merge the values of two dictionaries and add the values of common keys at the time of merging. Counter() method is used in the script to add the values of common keys.

# Import Counter module
from collections import Counter

# Declare two dictionaries
store1 = {'Pen': 150, 'Pencil': 250, 'Note Book': 100}
store2 = {'Eraser': 80, 'Pen': 50, 'Sharpner': 30, 'Pencil': 100}
 
# Merge the values of dictionaries based on common keys
mrgDic=Counter(store1)+Counter(store2)
 
# Print the keys and values of the merged dictionary
for val in mrgDic:
  print(val,':',mrgDic[val])

Output:

Run the script. Here, one dictionary contains three elements and another dictionary contains four elements. Two keys are common in two dictionaries.

Conclusion:

You can merge two or more dictionaries based on your programming requirements. I hope, merging dictionaries will be an easy task for python users after practicing the above examples.



from Linux Hint https://ift.tt/3aYiWIi

Post a Comment

0 Comments