Python | Combine the values of two dictionaries having same key - GeeksforGeeks (2024)

Last Updated : 21 Apr, 2023

Summarize

Comments

Improve

Dictionary is a collection which is unordered, changeable and indexed. In Python, dictionaries are written with curly brackets, and they have keys and values. It is widely used in day to day programming, web development, and machine learning. Combining dictionaries is very common task in operations of dictionary. Let’s see how to combine the values of two dictionaries having same key.

Method #1: Using Counter

Counter is a special subclass of dictionary that performs acts same as dictionary in most cases.

Step-by-step approach:

  • Import the Counter class from the collections module.
  • Define two dictionaries called “ini_dictionary1” and “ini_dictionary2” with some key-value pairs.
  • Print the initial dictionaries using the print() function.
  • Combine the two dictionaries using the “+” operator and the Counter() function.
  • Store the resulting dictionary in a variable called “final_dictionary”.
  • Print the final dictionary using the print() function.

Below is the implementation of the above approach:

Python3

# Python code to demonstrate combining

# two dictionaries having same key

from collections import Counter

# initialising dictionaries

ini_dictionary1 = Counter({'nikhil': 1, 'akash' : 5,

'manjeet' : 10, 'akshat' : 15})

ini_dictionary2 = Counter({'akash' : 7, 'akshat' : 5,

'm' : 15})

# printing initial dictionaries

print ("initial 1st dictionary", str(ini_dictionary1))

print ("initial 2nd dictionary", str(ini_dictionary2))

# combining dictionaries

# using Counter

final_dictionary = ini_dictionary1 + ini_dictionary2

# printing final result

print ("final dictionary", str(final_dictionary))

Output

initial 1st dictionary Counter({'akshat': 15, 'manjeet': 10, 'akash': 5, 'nikhil': 1})initial 2nd dictionary Counter({'m': 15, 'akash': 7, 'akshat': 5})final dictionary Counter({'akshat': 20, 'm': 15, 'akash': 12, 'manjeet': 10, 'nikhil': 1})

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2: Using dict() and items This method is for Python version 2.

Step-by-step approach:

  • Two dictionaries are initialized with key-value pairs, stored in the variables ini_dictionary1 and ini_dictionary2 respectively.
  • The initial dictionaries are printed using the print() function, to show their content before combining.
  • The dictionaries are combined into a final dictionary, using the dict() constructor and the items() method.
  • This creates a new dictionary that includes all the key-value pairs from both initial dictionaries.
  • To handle cases where the same key exists in both initial dictionaries, a list comprehension is used to iterate over the set intersection of the keys in both dictionaries (i.e., the keys that exist in both dictionaries). For each of these keys, a new tuple is created with the key and the sum of the values for that key in both dictionaries. This tuple is then added to the list of key-value pairs being passed to the dict() constructor, so that it gets included in the final dictionary.
  • The final dictionary is printed using the print() function. It includes all the key-value pairs from both initial dictionaries, as well as any key-value pairs where the same key exists in both initial dictionaries (with the values added together).

Below is the implementation of the above approach:

Python

# Python code to demonstrate combining

# two dictionaries having same key

# initialising dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash' : 5,

'manjeet' : 10, 'akshat' : 15}

ini_dictionary2 = {'akash' : 7, 'akshat' : 5,

'm' : 15}

# printing initial dictionaries

print ("initial 1st dictionary", str(ini_dictionary1))

print ("initial 2nd dictionary", str(ini_dictionary2))

# combining dictionaries

# using dict() and items()

final_dictionary = dict(ini_dictionary1.items() + ini_dictionary2.items() +

[(k, ini_dictionary1[k] + ini_dictionary2[k])

for k in set(ini_dictionary2)

& set(ini_dictionary1)])

# printing final result

print ("final dictionary", str(final_dictionary))

Output

('initial 1st dictionary', "{'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5}")('initial 2nd dictionary', "{'m': 15, 'akshat': 5, 'akash': 7}")('final dictionary', "{'nikhil': 1, 'm': 15, 'manjeet': 10, 'akshat': 20, 'akash': 12}")

Time complexity: O(n), where n is the number of elements in both dictionaries.
Auxiliary space: O(n), where n is the size of the final dictionary created by combining both dictionaries.

Method #3: Using dict comprehension and set

Python3

# Python code to demonstrate combining

# two dictionaries having same key

# initialising dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash' : 5,

'manjeet' : 10, 'akshat' : 15}

ini_dictionary2 = {'akash' : 7, 'akshat' : 5,

'm' : 15}

# printing initial dictionaries

print ("initial 1st dictionary", str(ini_dictionary1))

print ("initial 2nd dictionary", str(ini_dictionary2))

# combining dictionaries

# using dict comprehension and set

final_dictionary = {x: ini_dictionary1.get(x, 0) + ini_dictionary2.get(x, 0)

for x in set(ini_dictionary1).union(ini_dictionary2)}

# printing final result

print ("final dictionary", str(final_dictionary))

Output

initial 1st dictionary {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}initial 2nd dictionary {'akash': 7, 'akshat': 5, 'm': 15}final dictionary {'m': 15, 'manjeet': 10, 'akshat': 20, 'nikhil': 1, 'akash': 12}

Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(n), where n is the total number of key-value pairs in both dictionaries

Method #4: Using dict() and for loop

Combine two dictionaries with the same keys using a for loop and the dict() constructor to create a new dictionary.

Python3

# initialising dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}

ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15}

# combining dictionaries using a for loop and dict() constructor

final_dictionary = {}

for key in ini_dictionary1:

final_dictionary[key] = ini_dictionary1[key] + ini_dictionary2.get(key, 0)

for key in ini_dictionary2:

if key not in final_dictionary:

final_dictionary[key] = ini_dictionary2[key]

# printing final result

print("final dictionary", str(final_dictionary))

Output

final dictionary {'nikhil': 1, 'akash': 12, 'manjeet': 10, 'akshat': 20, 'm': 15}

Time complexity: O(n), where n is the total number of key-value pairs in both dictionaries.
Auxiliary space: O(n), where n is the total number of key-value pairs in both dictionaries

Method #5: use the update() method.

Step-by-step approach:

  • Define the initial dictionaries:
  • Create a new dictionary and update it with the first dictionary.
  • Use the update() method to add or update the key-value pairs from the second dictionary:
  • If there are keys in the second dictionary that are not in the first one, they will be added to the final dictionary automatically.
  • Print the final result.

Below is the implementation of the above approach:

Python3

# initialising dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}

ini_dictionary2 = {'akash': 7, 'akshat': 5, 'm': 15}

# combining dictionaries using update() method

final_dictionary = ini_dictionary1.copy()

final_dictionary.update(ini_dictionary2)

# printing final result

print("final dictionary", str(final_dictionary))

Output

final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time complexity: O(n+m), where n and m are the sizes of the two dictionaries.
Auxiliary space: O(n), where n is the size of the first dictionary.

Method #6: Using the ** operator

Step-by-step approach:

  • Define two dictionaries called ini_dictionary1 and ini_dictionary2 with some key-value pairs.
  • Create a new dictionary called final_dictionary by using the double asterisk operator (**) to unpack the two dictionaries into a single dictionary.
  • Print the final result using the print() function and passing the string representation of final_dictionary.

Below is the implementation of the above approach:

Python3

# initializing dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}

ini_dictionary2 = {'akash': 7, 'akshat': 5, 'm': 15}

# combining dictionaries using the ** operator

final_dictionary = {**ini_dictionary1, **ini_dictionary2}

# printing final result

print("final dictionary", str(final_dictionary))

Output

final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time complexity: O(n), where n is the total number of elements in both dictionaries.
Auxiliary space: O(n), where n is the total number of elements in both dictionaries.

Method #7: Using Merge Operator

Step-by-Step Approach:

  • Initialize an empty dictionary to store the combined result.
  • Use the merge operator (**), which combines two dictionaries into a single dictionary, to merge the two dictionaries ini_dictionary1 and ini_dictionary2.
  • For each key in the merged dictionary, sum up the values for the same keys.
  • Store the result in the final dictionary.
  • Print the final dictionary.

Python3

# initialising dictionaries

ini_dictionary1 = {'nikhil': 1, 'akash' : 5, 'manjeet' : 10, 'akshat' : 15}

ini_dictionary2 = {'akash' : 7, 'akshat' : 5, 'm' : 15}

# printing initial dictionaries

print ("initial 1st dictionary", str(ini_dictionary1))

print ("initial 2nd dictionary", str(ini_dictionary2))

# combining dictionaries using merge operator

merged_dict = {**ini_dictionary1, **ini_dictionary2}

final_dict = {}

for key, value in merged_dict.items():

final_dict[key] = final_dict.get(key, 0) + value

# printing final result

print ("final dictionary", str(final_dict))

Output

initial 1st dictionary {'nikhil': 1, 'akash': 5, 'manjeet': 10, 'akshat': 15}initial 2nd dictionary {'akash': 7, 'akshat': 5, 'm': 15}final dictionary {'nikhil': 1, 'akash': 7, 'manjeet': 10, 'akshat': 5, 'm': 15}

Time Complexity: O(m+n), where m and n are the number of items in the two dictionaries.
Auxiliary Space: O(m+n), where m and n are the number of items in the two dictionaries.



garg_ak0109

Python | Combine the values of two dictionaries having same key - GeeksforGeeks (2)

Improve

Next Article

Python - Combine two dictionaries having key of the first dictionary and value of the second dictionary

Please Login to comment...

Python | Combine the values of two dictionaries having same key - GeeksforGeeks (2024)
Top Articles
Personal Finance Company - Mariner Finance
Open an International Bank Account - HSBC International
Exclusive: Baby Alien Fan Bus Leaked - Get the Inside Scoop! - Nick Lachey
My E Chart Elliot
Mcoc Immunity Chart July 2022
Autobell Car Wash Hickory Reviews
Bloxburg Image Ids
Mail Healthcare Uiowa
Osrs But Damage
ds. J.C. van Trigt - Lukas 23:42-43 - Preekaantekeningen
Pwc Transparency Report
Crusader Kings 3 Workshop
Edible Arrangements Keller
Https //Advanceautoparts.4Myrebate.com
Wordle auf Deutsch - Wordle mit Deutschen Wörtern Spielen
Jackson Stevens Global
7 Fly Traps For Effective Pest Control
Simplify: r^4+r^3-7r^2-r+6=0 Tiger Algebra Solver
Kürtçe Doğum Günü Sözleri
Po Box 35691 Canton Oh
Farmer's Almanac 2 Month Free Forecast
Breckie Hill Mega Link
Pokemon Unbound Shiny Stone Location
How Long After Dayquil Can I Take Benadryl
Caring Hearts For Canines Aberdeen Nc
Defending The Broken Isles
Spiritual Meaning Of Snake Tattoo: Healing And Rebirth!
Divina Rapsing
Soul Eater Resonance Wavelength Tier List
Garden Grove Classlink
NV Energy issues outage watch for South Carson City, Genoa and Glenbrook
How To Improve Your Pilates C-Curve
Nurofen 400mg Tabletten (24 stuks) | De Online Drogist
Otis Offender Michigan
Que Si Que Si Que No Que No Lyrics
Http://N14.Ultipro.com
Rvtrader Com Florida
Marine Forecast Sandy Hook To Manasquan Inlet
Unity Webgl Player Drift Hunters
Hannibal Mo Craigslist Pets
How To Get Soul Reaper Knife In Critical Legends
Dying Light Nexus
Zasilacz Dell G3 15 3579
Aita For Announcing My Pregnancy At My Sil Wedding
Citibank Branch Locations In North Carolina
What to Do at The 2024 Charlotte International Arts Festival | Queen City Nerve
Bekkenpijn: oorzaken en symptomen van pijn in het bekken
Hawkview Retreat Pa Cost
Rescare Training Online
Sam's Club Gas Price Sioux City
Puss In Boots: The Last Wish Showtimes Near Valdosta Cinemas
Mkvcinemas Movies Free Download
Latest Posts
Article information

Author: Twana Towne Ret

Last Updated:

Views: 5365

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Twana Towne Ret

Birthday: 1994-03-19

Address: Apt. 990 97439 Corwin Motorway, Port Eliseoburgh, NM 99144-2618

Phone: +5958753152963

Job: National Specialist

Hobby: Kayaking, Photography, Skydiving, Embroidery, Leather crafting, Orienteering, Cooking

Introduction: My name is Twana Towne Ret, I am a famous, talented, joyous, perfect, powerful, inquisitive, lovely person who loves writing and wants to share my knowledge and understanding with you.