Python – 将键值分配给值列表字典中的列表元素
给定元素列表,将它们与值列表中匹配值的键映射。
Input : test_list = [4, 6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [8, 4]}
Output : [‘is’, ‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]
Explanation : 4 is present in “is” key, hence mapped in new list.
Input : test_list = [6, 3, 5, 3], test_dict = {“Gfg” : [5, 3, 6], “is” : [18, 14]}
Output : [‘Gfg’, ‘Gfg’, ‘Gfg’, ‘Gfg’]
Explanation : All elements present in “Gfg” key.
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们提取字典值列表的每个元素以检查列表值的出现,如果匹配,我们将该键的值分配给该索引。
Python3
# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using list comprehension
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
# nested loop inside list comprehension to check each key
res = [key for ele in test_list
for key, val in test_dict.items() if ele in val]
# printing result
print("The filtered list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using dictionary comprehension + list comprehension
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
# creating inverse dictionary of elements
temp = {j : i for i, k in test_dict.items() for j in k}
# creating end result by mapping elements
res = [temp.get(key) for key in test_list]
# printing result
print("The filtered list : " + str(res))
输出
The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']
方法#2:使用字典理解+列表理解
这是可以执行此任务的另一种方式。在此我们创建逆字典,并将每个列表值与其键映射,然后将每个键映射到参数键列表元素以匹配键值。
Python3
# Python3 code to demonstrate working of
# Assigning Key values to list elements from Value list Dictionary
# Using dictionary comprehension + list comprehension
# initializing list
test_list = [4, 6, 3, 10, 5, 3]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
test_dict = {"Gfg" : [5, 3, 6], "is" : [8, 4], "Best" : [10, 11]}
# creating inverse dictionary of elements
temp = {j : i for i, k in test_dict.items() for j in k}
# creating end result by mapping elements
res = [temp.get(key) for key in test_list]
# printing result
print("The filtered list : " + str(res))
输出
The original list : [4, 6, 3, 10, 5, 3]
The filtered list : ['is', 'Gfg', 'Gfg', 'Best', 'Gfg', 'Gfg']