[英]Extracting an unspecified number of dictionaries named after keys in dictionary (Python)
晚上好,
相信一切都很好。
客觀的
我正在嘗試將字典分解為每個鍵的單獨字典; 每個新字典的值都是空白的。 稍后將使用 zip function 列表填充字典。
我的嘗試
初始列表 (list_towers) 將包含不同數量的值和未指定數量的重復值。 下面代碼中的值對於我的問題是有限的。
刪除所有重復值后,我留下了一個列表 (unique_towers),然后將其壓縮到字典 (unique_towers_dict) 中。 所有鍵都有空白值。
我想不出一個 for 循環來遍歷 unique_towers_dict 以為每個鍵創建一個單獨的字典。
任何反饋將不勝感激!
我的注釋代碼如下
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)
Output
{'Tower1': {}, 'Tower2': {}, 'Tower3': {}, 'Tower4': {}, 'Tower5': {}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.