Python - 组合两个字典,具有第一个字典的键和第二个字典的值
给出两本词典。任务是以这样一种方式合并它们,即生成的字典包含来自第一个字典的键和来自第二个字典的值。
例子:
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.
方法#1:使用循环+keys()
这是可以执行此任务的一种方式。在这里,我们使用 keys() 提取所有键,然后在循环内分配所需的值。
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))
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))
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}
方法#2:使用 zip() + values()
这是可以执行此任务的另一种方式。在这里,我们使用 zip() 执行映射任务,使用 values() 提取值。
蟒蛇3
# 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))
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}