How to combine two dictionaries in python using different methods

how-to-combine-two-dictionaries-in-python-using-different-methods

Python Dictionary is a data structure that used to store elements in key-value pairs. Unlike python list values in the dictionary are retrieved or stored using the key. Dictionary is declared using the curly braces {} and the key value pair separated by : colon.

combine two dictionaries using python for loop

mydict1 = {
    "car": 5,
    "bus": 3,
    "bike": 10
}

mydict2 = {
    "cycle": 4,
    "truck": 8,
    "car": 6
}

for key in mydict2:
    mydict1[key] = mydict2[key]

print("mydict1:", mydict1)

Output:
mydict1: {'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}

key car exists in both variable, we doing the merge operation if the key is not in the first mydict1 variable, it will add a new key value pair, if the key already exist in the dict it will update the value of the key.

This above example is a normal dictionaries merge example using loop, python have some inbuild features we can make use of it without doing for loop to combine dictionaries.

Dictionary Merge Operator

Using merge operator(|) it is easy to do the dictionary merge, its available from python 3.9

mydict1 = {
    "car": 5,
    "bus": 3,
    "bike": 10
}

mydict2 = {
    "cycle": 4,
    "truck": 8,
    "car": 6
}

print(mydict1 | mydict2)

Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}

Merging Dictionaries Using ** Operator

This operator is used to pack and unpacking arguments, we can use the unpacking operator to merge two dictionaries

mydict1 = {
    "car": 5,
    "bus": 3,
    "bike": 10
}

mydict2 = {
    "cycle": 4,
    "truck": 8,
    "car": 6
}

print({**mydict1, **mydict2})

Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}

Merging Dictionaries Using the update() Method

Python have a inbuild method called update which is used to merge or add one dictionary to another

mydict1 = {
    "car": 5,
    "bus": 3,
    "bike": 10
}

mydict2 = {
    "cycle": 4,
    "truck": 8,
    "car": 6
}

mydict1.update(mydict2)
print(mydict1)

Output:
{'car': 6, 'bus': 3, 'bike': 10, 'cycle': 4, 'truck': 8}

Using unpacking operator(**) and merge operator(|) only return the value where as here using the update method will update the values to the targeted variable.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
from-a-dumb-student-to-a-pytorch-contributor:-the-impact-of-teachers-on-my-life

From a Dumb Student to a PyTorch Contributor: The Impact of Teachers on My Life⚡

Next Post
homosexual-astrology-lesbian-compatibility-love-recommendation-relationship-help

Homosexual Astrology Lesbian Compatibility Love Recommendation Relationship Help

Related Posts