📌  相关文章
📜  Python – 将值分配给值列表

📅  最后修改于: 2022-05-13 01:55:15.704000             🧑  作者: Mango

Python – 将值分配给值列表

给定 2 个字典,将值分配给从字典 2 映射的值列表元素。

方法#1:使用嵌套字典理解

在此,我们使用内部字典理解将值元素映射到字典 2,外部字典用于从字典 1 中提取所有键。

Python3
# Python3 code to demonstrate working of 
# Assign values to Values List
# Using nested dictionary comprehension
  
# initializing dictionary
test_dict = {'Gfg' : [3, 6],
             'is' : [4, 2], 
             'best' :[9]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing lookup dict 
look_dict = {3 : [1, 5], 6 : "Best", 4 : 10, 9 : 12, 2 : "CS"}
  
# nested dictionaries to sought solution
res = {idx: {ikey: look_dict[ikey] for ikey in test_dict[idx]} for idx in test_dict}
  
# printing result 
print("The mapped dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of
# Assign values to Values List
# Using items() + dictionary comprehension
  
# initializing dictionary
test_dict = {'Gfg': [3, 6],
             'is': [4, 2],
             'best': [9]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing lookup dict
look_dict = {3: [1, 5], 6: "Best", 4: 10, 9: 12, 2: "CS"}
  
# nested dictionaries to sought solution
# items() used to access key-val pairs
res = {key: {ikey: ival for (ikey, ival) in look_dict.items(
) if ikey in val} for (key, val) in test_dict.items()}
  
# printing result
print("The mapped dictionary : " + str(res))


输出
The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}

方法 #2:使用 items() + 字典理解

与上述方法类似,另一个单行,不同之处在于 items() 用于元素访问。

Python3

# Python3 code to demonstrate working of
# Assign values to Values List
# Using items() + dictionary comprehension
  
# initializing dictionary
test_dict = {'Gfg': [3, 6],
             'is': [4, 2],
             'best': [9]}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing lookup dict
look_dict = {3: [1, 5], 6: "Best", 4: 10, 9: 12, 2: "CS"}
  
# nested dictionaries to sought solution
# items() used to access key-val pairs
res = {key: {ikey: ival for (ikey, ival) in look_dict.items(
) if ikey in val} for (key, val) in test_dict.items()}
  
# printing result
print("The mapped dictionary : " + str(res))
输出
The original dictionary is : {'Gfg': [3, 6], 'is': [4, 2], 'best': [9]}
The mapped dictionary : {'Gfg': {3: [1, 5], 6: 'Best'}, 'is': {4: 10, 2: 'CS'}, 'best': {9: 12}}