提取唯一字典值列表元素的Python程序
给定带有值列表的字典,提取所有唯一值。
Input : test_dict = {“Gfg” : [6, 7, 4, 6], “Geeks” : [6, 8, 5, 2]}
Output : [6, 7, 4, 8, 5, 2]
Explanation : All distincts elements extracted.
Input : test_dict = {“Gfg” : [6, 7, 6], “Geeks” : [6, 8, 5, 2]}
Output : [6, 7, 8, 5, 2]
Explanation : All distincts elements extracted.
方法#1:使用循环
这是执行此任务的蛮力方式。在这种情况下,我们在元素出现时记住它们并防止它们重新进入结果列表。
Python3
# Python3 code to demonstrate working of
# Unique Dictionary Value List elements
# Using loop
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 4, 6],
"is" : [8, 9, 5],
"for" : [2, 5, 3, 7],
"Geeks" : [6, 8, 5, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# list to memorize elements and insert result
res = []
for sub in test_dict:
for ele in test_dict[sub]:
# testing for existence
if ele not in res:
res.append(ele)
# printing result
print("Extracted items : " + str(res))
Python3
# Python3 code to demonstrate working of
# Unique Dictionary Value List elements
# Using set() + union()
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 4, 6],
"is" : [8, 9, 5],
"for" : [2, 5, 3, 7],
"Geeks" : [6, 8, 5, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using * operator to get union
res = list(set().union(*test_dict.values()))
# printing result
print("Extracted items : " + str(res))
输出:
The original dictionary is : {‘Gfg’: [6, 7, 4, 6], ‘is’: [8, 9, 5], ‘for’: [2, 5, 3, 7], ‘Geeks’: [6, 8, 5, 2]}
Extracted items : [6, 7, 4, 8, 9, 5, 2, 3]
方法 #2:使用set() + union()
以上功能的组合可以解决这个问题。在这种情况下,我们使用 set() 转换所有列表,然后对所有键执行所有元素的并集以获得所需的结果。
蟒蛇3
# Python3 code to demonstrate working of
# Unique Dictionary Value List elements
# Using set() + union()
# initializing dictionary
test_dict = {"Gfg" : [6, 7, 4, 6],
"is" : [8, 9, 5],
"for" : [2, 5, 3, 7],
"Geeks" : [6, 8, 5, 2]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using * operator to get union
res = list(set().union(*test_dict.values()))
# printing result
print("Extracted items : " + str(res))
输出:
The original dictionary is : {‘Gfg’: [6, 7, 4, 6], ‘is’: [8, 9, 5], ‘for’: [2, 5, 3, 7], ‘Geeks’: [6, 8, 5, 2]}
Extracted items : [6, 7, 4, 8, 9, 5, 2, 3