Python|将集合转换为字典
有时,我们需要将一种数据结构转换为另一种数据结构,以应对日常编码和 Web 开发中的各种操作和问题。就像我们可能想从给定的集合元素中获取字典一样。
让我们讨论一些将给定集合转换为字典的方法。
方法 #1:使用 fromkeys()
Python3
# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
# Converting set to dictionary
res = dict.fromkeys(ini_set, 0)
# printing final result and its type
print ("final list", res)
print (type(res))
Python3
# Python code to demonstrate
# converting set into dictionary
# using dict comprehension
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
str = 'fg'
# Converting set to dict
res = {element:'Geek'+str for element in ini_set}
# printing final result and its type
print ("final list", res)
print (type(res))
输出:
initial string {1, 2, 3, 4, 5}
final list {1: 0, 2: 0, 3: 0, 4: 0, 5: 0}
方法 #2:使用 dict 理解
Python3
# Python code to demonstrate
# converting set into dictionary
# using dict comprehension
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print ("initial string", ini_set)
print (type(ini_set))
str = 'fg'
# Converting set to dict
res = {element:'Geek'+str for element in ini_set}
# printing final result and its type
print ("final list", res)
print (type(res))
输出:
initial string {1, 2, 3, 4, 5}
final list {1: 'Geek', 2: 'Geek', 3: 'Geek', 4: 'Geek', 5: 'Geek'}