Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Combine two dictionaries having key of the first dictionary and...

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

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.

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments