[英]create nested dictionary using list
我想創建一個很長的嵌套字典,但有些不是創建新項目,而是不斷更新最后一個項目。
sessions = ['S0_DO','S1_DO','S2_DO','S3_DO','S4_DO','S5_DO']
groups = ['All','Aggregator','Non-Aggregator']
comparator = {}
for session in sessions:
for group in groups:
c = {
"time" : "2019-09-20 10:30:00",
session :{
group:{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
}
}
comparator.update(c)
所有會話都已創建,但是當涉及到組時,字典中只有列表的最后一項。 它只是更新而不是創建新的。
我怎樣才能解決這個問題 ?
謝謝
所需的輸出:
comparator = {
"time" : "2019-09-20 10:30:00",
"S0_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
},
"S1_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
},
"S2_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
},
"S3_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
},
"S4_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
},
"S5_DO" :{
"All":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
},
"Non-Aggregator":{
"std":0,
"mean":0,
"upper_limit":0,
"lower_limit":0,
"actual":0,
"anomaly":0
}
}
}
在group
循環的每次迭代中,您使用僅包含該單個 group 的新 dict 覆蓋session
key 的 value,因此所有 session 都以最后一個 group 結束。 您可能想用字典理解替換內部循環。
comparator = {"time": "2019-09-20 10:30:00"}
for session in sessions:
c = {
session: {
group: {
"std": 0,
"mean": 0,
"upper_limit": 0,
"lower_limit": 0,
"actual": 0,
"anomaly": 0,
}
for group in groups
}
}
comparator.update(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.