Open In App

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

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two dictionaries. The task is to merge them in such a way that the resulting dictionary contains the key from the first dictionary and the value from the second dictionary.

Examples:

Input : test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}, 
test_dict2 = {"Gfg2" : 26, "is2" : 20, "best2" : 70} 
Output : {'Gfg': 26, 'is': 20, 'best': 70} 
Explanation : Similar index keys' values assigned to dictionary 1.
Input : test_dict1 = {"Gfg" : 20, "best" : 100}, test_dict2 = {"Gfg2" : 26, "best2" : 70} 
Output : {'Gfg': 26, 'best': 70} 
Explanation : Similar index keys' values assigned to dictionary 1. 

Method #1 : Using loop + keys()

This is one way in which this task can be performed. In this, we extract all the keys using keys() and then assign required values inside loop.

Step-by-step approach :

  • Extract the keys from test_dict1 using the keys() method, and store them in a list called keys1.
  • Extract the values from test_dict2 using the values() method, and store them in a list called vals2.
  • Initialize an empty dictionary called res.
  • Loop through the range of the length of keys1.
    • For each iteration, assign the value of the idx-th element in keys1 as a key, and the value of the idx-th element in vals2 as the value to the res dictionary.
  • Print the final mapped dictionary, res.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using loop + keys()
 
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# extracting keys and values
keys1 = list(test_dict1.keys())
vals2 = list(test_dict2.values())
 
# assigning new values
res = dict()
for idx in range(len(keys1)):
    res[keys1[idx]] = vals2[idx]
     
# printing result
print("Mapped dictionary : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

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

Method #2 : Using zip() + values()

This is yet another way in which this task can be performed. In this, we perform the task of mapping using zip(), extracting values using values().

Step-by-step approach:

  1. Initialize two dictionaries test_dict1 and test_dict2.
  2. Print the original dictionaries.
  3. Use the zip() function to combine the keys of test_dict1 with the values of test_dict2 and create a new dictionary.
  4. Print the resulting dictionary.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using zip() + values()
 
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# using zip() to perform required dict. mapping
res = dict(zip(test_dict1, test_dict2.values()))
     
# printing result
print("Mapped dictionary : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

Time complexity: O(n)
Auxiliary space: O(n) (for the resultant dictionary)

Method #3: Using enumerate() and loop:

we loop through the keys of the first dictionary using enumerate(), which gives us an index and the key itself on each iteration. We then check if the index is within the range of the second dictionary’s values (to avoid an index out of range error), and if so, we assign the corresponding value from the second dictionary to the new dictionary using the current key. Finally, we print the resulting dictionary.

Python3




# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# assigning new values
res = dict()
for idx, key in enumerate(test_dict1.keys()):
    if idx < len(test_dict2):
        res[key] = list(test_dict2.values())[idx]
 
# printing result
print("Mapped dictionary : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

Time complexity: O(n)
Auxiliary space: O(n) 

Method #4: Using dictionary comprehension and zip()

Use a dictionary comprehension to create a new dictionary with the same keys as test_dict1 and the values from test_dict2. We do this by using the zip() function to iterate over both dictionaries simultaneously, extracting the keys from test_dict1 and the values from test_dict2. Finally, we use dictionary comprehension to create the new dictionary res with the key-value pairs.

Python3




# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# using dictionary comprehension and zip to assign new values
res = {k: v2 for k, v2 in zip(test_dict1.keys(), test_dict2.values())}
 
# printing result
print("Mapped dictionary : " + str(res))


Output

Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

Time complexity: O(n)
Auxiliary space: O(n)

Method #5: Using dictionary comprehension and items()

Use dictionary comprehension along with the items() method to extract the key-value pairs from both dictionaries simultaneously. The zip() function is used to pair up the corresponding key-value pairs from both dictionaries. The resulting pairs are then used in the dictionary comprehension to create a new dictionary with the keys from the first dictionary and values from the second dictionary. This method has a time complexity of O(n), where n is the size of the dictionaries.

Approach:

  1. Initialize a dictionary named “test_dict” with some key-value pairs.
  2. Print the original dictionary using the “print()” function and string concatenation.
  3. Initialize a variable “K” with the number of items to be returned from the dictionary.
  4. Initialize an empty dictionary named “res”.
  5. Use a for loop with “test_dict.items()” to iterate over the key-value pairs of the dictionary.
  6. Check if the length of “res” is less than “K”. If so, add the key-value pair to the “res” dictionary using the key as the index and the value as the value.
  7. If the length of “res” is equal to or greater than “K”, break out of the loop.
  8. Print the final dictionary named “res” limited to the first K items.

Python3




# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using dictionary comprehension and items()
 
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# assigning new values using dictionary comprehension and items()
res = {k: v2 for (k, v1), (k2, v2) in zip(test_dict1.items(), test_dict2.items())}
 
# printing result
print("Mapped dictionary : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

Time complexity: O(n) 
where n is the size of the dictionaries. This is because the method uses a single loop over the key-value pairs of the dictionaries and creates a new dictionary using dictionary comprehension.
Auxiliary space: O(n)
where n is the size of the dictionaries.

Method #6: Using dictionary comprehension and zip().

Approach:

  1. Initialize dictionaries test_dict1 and test_dict2 with the given key-value pairs.
  2. Print the original dictionaries.
  3. Use the zip() function to create an iterator that aggregates the values of test_dict1 and test_dict2 by their corresponding indices. This will create a sequence of tuples that contain corresponding key-value pairs from both dictionaries.
  4. Use dictionary comprehension to create a new dictionary by iterating over the tuples and extracting the key from the first dictionary and the value from the second dictionary.
  5. Print the resulting dictionary.

Python3




# Python3 code to demonstrate working of
# Assign similar index values in Dictionary
# Using dictionary comprehension and zip()
 
# initializing dictionaries
test_dict1 = {"Gfg" : 20, "is" : 36, "best" : 100}
test_dict2 = {"Gfg2" : 26, "is2" : 19, "best2" : 70}
 
# printing original dictionaries
print("The original dictionary 1 is : " + str(test_dict1))
print("The original dictionary 2 is : " + str(test_dict2))
 
# assigning new values
res = {k: v2 for k, v2 in zip(test_dict1.keys(), test_dict2.values())}
     
# printing result
print("Mapped dictionary : " + str(res))


Output

The original dictionary 1 is : {'Gfg': 20, 'is': 36, 'best': 100}
The original dictionary 2 is : {'Gfg2': 26, 'is2': 19, 'best2': 70}
Mapped dictionary : {'Gfg': 26, 'is': 19, 'best': 70}

Time complexity: O(n), where n is the number of key-value pairs in test_dict1 and test_dict2.
Auxiliary space: O(n), where n is the number of key-value pairs in test_dict1 and test_dict2.



Similar Reads

Python | Combine the values of two dictionaries having same key
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
7 min read
Python - Convert Dictionaries List to Order Key Nested dictionaries
Given list of dictionaries, convert to ordered key dictionary with each key contained dictionary as its nested value. Input : test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}] Output : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}} Explanation : List converted to dictionary with index keys. Input : test_list = [{"is": 8, "Good" : 2}] Output :
6 min read
Python Program to extract Dictionaries with given Key from a list of dictionaries
Given a list of dictionaries, the task is to write a python program that extracts only those dictionaries that contain a specific given key value. Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3}], key= "gfg"Output : [{'gfg': 2, 'is': 8, 'good': 3}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}] Expl
6 min read
Convert Dictionary of Dictionaries to Python List of Dictionaries
Dictionaries are powerful data structures in Python, allowing the storage of key-value pairs. Sometimes, we encounter scenarios where we have a dictionary of dictionaries, and we need to convert it into a list of dictionaries for easier manipulation or processing. In this article, we'll explore five different methods to achieve this conversion, eac
3 min read
Combine keys in a list of dictionaries in Python
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform a merge of dictionaries in list with similar keys. This kind of problem can come in data optimization domains. Let's discuss a way in which this task can be performed. Input : test_list = [{'a': 6}, {'b': 2}, {'a': 9}, {'b': 7}] Output : [{'b': 2, '
2 min read
Python | Sort Python Dictionaries by Key or Value
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python. Need for Sorting Dictionary in PythonWe need sorting of data to reduce the complexity of the data and make queries faster and more eff
5 min read
Python - Extract Key's Value, if Key Present in List and Dictionary
Given a list, dictionary, and a Key K, print the value of K from the dictionary if the key is present in both, the list and the dictionary. Input : test_list = ["Gfg", "is", "Good", "for", "Geeks"], test_dict = {"Gfg" : 5, "Best" : 6}, K = "Gfg" Output : 5 Explanation : "Gfg" is present in list and has value 5 in dictionary. Input : test_list = ["G
11 min read
Convert a List of Dictionaries into a Set of Dictionaries
Python's versatility allows developers to manipulate data in various ways. When working with a list of dictionaries, there might be scenarios where you want to convert it into a set of dictionaries to eliminate duplicates or for other reasons. In this article, we'll explore three different methods to achieve this goal with code examples. Convert A
3 min read
Python | Segregating key's value in list of dictionaries
While working with dictionaries, we may encounter problems in which we need to segregate all the similar keys' values together. This kind of problem can occur in web development domain while working with databases. Let's discuss certain ways in which this problem can be solved. Method #1: Using generator expression A generator expression can be use
6 min read
Python - Sort dictionaries list by Key's Value list index
Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}, {'Gfg': [6, 7, 8],
14 min read
Practice Tags :