Python - 从字典值设置
给定一个字典,任务是编写一个Python程序来获取所有值并转换为集合。
例子:
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 3, ‘best’ : 7, ‘for’ : 3, ‘geek’ : 4}
Output : {3, 4, 7}
Explanation : 2nd occurrence of 3 is removed in transformation phase.
Input : test_dict = {‘Gfg’ : 4, ‘is’ : 3, ‘best’ : 7, ‘geek’ : 4}
Output : {3, 4, 7}
Explanation : 2nd occurrence of 4 is removed in transformation phase.
方法 #1:使用生成器表达式 + {}
在这里,我们使用生成器表达式执行获取所有值的任务,{}运算符执行删除重复元素和转换为集合的任务。
Python3
# Python3 code to demonstrate working of
# Set from dictionary values
# Using generator expression + {}
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# {} converting to set
res = {test_dict[sub] for sub in test_dict}
# printing result
print("The converted set : " + str(res))
Python3
# Python3 code to demonstrate working of
# Set from dictionary values
# Using values() + set()
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values() used to get values
res = set(test_dict.values())
# printing result
print("The converted set : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: 3, ‘best’: 7, ‘for’: 3, ‘geek’: 4}
The converted set : {3, 4, 7}
方法#2:使用values() + set()
在这里,我们使用 values() 执行从字典中获取值的任务,set() 用于转换为 set。
蟒蛇3
# Python3 code to demonstrate working of
# Set from dictionary values
# Using values() + set()
# initializing dictionary
test_dict = {'Gfg': 4, 'is': 3, 'best': 7, 'for': 3, 'geek': 4}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# values() used to get values
res = set(test_dict.values())
# printing result
print("The converted set : " + str(res))
输出:
The original dictionary is : {‘Gfg’: 4, ‘is’: 3, ‘best’: 7, ‘for’: 3, ‘geek’: 4}
The converted set : {3, 4, 7}