提取字典(Python)中以键命名的未指定数量的字典
晚上好, 相信一切都好 目标 我试图将一个字典分解为每个键的单独字典;每个新字典的值都将为空。字典将在稍后阶段使用zip函数填充列表 我的尝试 初始列表(list_towers)将包含不同数量的值和未指定数量的重复值。下面代码中的值对于我的问题是有限的 删除所有重复值后,我会留下一个列表(unique_towers),然后将其压缩到字典(unique_towers_dict)中。所有键都有空白值 我无法找到一个for循环来迭代唯一的目录,为每个键创建一个单独的字典 任何反馈都将不胜感激 我的注释代码如下提取字典(Python)中以键命名的未指定数量的字典,python,dictionary,split,nested,Python,Dictionary,Split,Nested,晚上好, 相信一切都好 目标 我试图将一个字典分解为每个键的单独字典;每个新字典的值都将为空。字典将在稍后阶段使用zip函数填充列表 我的尝试 初始列表(list_towers)将包含不同数量的值和未指定数量的重复值。下面代码中的值对于我的问题是有限的 删除所有重复值后,我会留下一个列表(unique_towers),然后将其压缩到字典(unique_towers_dict)中。所有键都有空白值 我无法找到一个for循环来迭代唯一的目录,为每个键创建一个单独的字典 任何反馈都将不胜感激 我的注释
from collections import OrderedDict
#The list in reality would have a varying number of values, and an unspecified number of duplicate values
list_towers = ["Tower1", "Tower1", "Tower2", "Tower3", "Tower3", "Tower4", "Tower5", "Tower5"]
print(f"Complete list of Tower values: {list_towers}\n") #prints list of towers; includes duplicates
unique_num_towers = len(set(list_towers)) #extract number of unique values in the set
print(f"Number of Unique Towers: {unique_num_towers}") #prints the unique number of towers
unique_towers = (set(list_towers)) #extracts a unique values from list_towers into the set unique_towers
unique_towers = list(unique_towers) #convert set unique_towers into a list
unique_towers.sort() #sort the list in ascending order
print(f"Names of unique towers in list: {unique_towers}\n")
unique_towers_dict = {} #create an empty dictionary unique_towers_dict
for unique_towers in zip(unique_towers): #assign the lists to the dict
unique_towers_dict[unique_towers] = [] #assign unique_towers as key; values are empty
print(f"Nested Dictionary: {unique_towers_dict}") #print dictionary; shows empty values; keys are in ascending order
#I can't figure out a for loop to iterate through the unique_towers_dict to create a separate dictionary for each key
如果我理解正确,这个循环应该得到正确的答案:
d = {}
for x in unique_towers_dict.keys():
d[x[0]] = {}
print ("\n", d)
输出
{'Tower1': {}, 'Tower2': {}, 'Tower3': {}, 'Tower4': {}, 'Tower5': {}}