📜  Python - 从字典值设置

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

Python - 从字典值设置

给定一个字典,任务是编写一个Python程序来获取所有值并转换为集合。

例子:

方法 #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))


输出:

方法#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))

输出: