我在使用 for 回圈在其他字典中創建具有多個鍵和值的字典時遇到問題。
我有一個程式可以讀取另一個文本檔案,然后將其資訊輸入到字典中。該檔案如下所示:
GPU;GeForce GTX 1070 Ti;430
CPU;AMD Ryzen 7 2700X;233
GPU;GeForce GTX 2060;400
CPU;Intel Core i7-11700;360
RAM;HyperX 16GB;180
PSU;Corsair RM850X;210
我想要實作的是,我正在嘗試為每個組件型別 {GPU、CPU、RAM、PSU 等} 創建一個字典,而對于那些我正在嘗試輸入另一個由多個鍵組成的字典和值為 {name1 : price1, name2 : price2, etc.} 運行程式后,完整的字典應如下所示:
"GPU": {"GeForce GTX 1070 Ti": 430, "GeForce GTX 2060 2": 233},
"CPU": {"AMD Ryzen 7 2700X": 233, "Intel Core i7-11700 : 360},
"RAM": {"HyperX 16GB": 180},
"PSU": {"Corsair RM850X": 210}
但相反,它看起來像這樣:
"GPU": {"GeForce GTX 2060 2": 233},
"CPU": {"Intel Core i7-11700 : 360},
"RAM": {"HyperX 16GB": 180},
"PSU": {"Corsair RM850X": 210}
問題是:我無法正確創建字典,因為新的內部鍵和值會相互覆寫。我怎樣才能讓這個回圈不這樣做,而只是在內部字典中一個接一個地添加新值?
這是我的代碼:
def main():
filename = input("Enter the component file name: ")
file = open(filename, mode="r")
# Defining the outer dict. This dict's keys are the component types and
# it's values are inner dictionaries.
outer_dict = {}
for row in file:
row = row.strip()
parts = row.split(";")
# Defining variables for each part per line.
type = parts[0]
name = parts[1]
price = int(parts[2])
# Defining the inner dict. This dict's keys are the component's name
# and it's price. There can be multiple names and prices in this dict.
inner_dict = {}
# Adding each name and price to the inner dictionaries.
for i in range(1, len(parts)):
inner_dict[name] = price
# Adding the created inner dict into the outer dictionary.
outer_dict[type] = inner_dict
file.close()
if __name__ == "__main__":
main()
提前感謝大家的幫助。真的很需要!
uj5u.com熱心網友回復:
您可以簡單地使用collections.defaultdict和 一個簡單的回圈來實作預期的行為。
注意。我在這里模擬一個帶有拆分文本的檔案
f = '''GPU;GeForce GTX 1070 Ti;430
CPU;AMD Ryzen 7 2700X;233
GPU;GeForce GTX 2060;400
CPU;Intel Core i7-11700;360
RAM;HyperX 16GB;180
PSU;Corsair RM850X;210'''
from collections import defaultdict
out = defaultdict(dict)
for line in f.split('\n'):
typ,name,price = line.split(';')
out[typ][name] = price
dict(out)
輸出:
>>> dict(out)
{'GPU': {'GeForce GTX 1070 Ti': '430', 'GeForce GTX 2060': '400'},
'CPU': {'AMD Ryzen 7 2700X': '233', 'Intel Core i7-11700': '360'},
'RAM': {'HyperX 16GB': '180'},
'PSU': {'Corsair RM850X': '210'}}
用一個檔案:
with open('file.txt') as f:
for line in f:
# rest of the loop from above
uj5u.com熱心網友回復:
是這部分。您正在替換字典鍵的值。
outer_dict[type] = inner_dict
而是將其更改為添加這樣的新子鍵
type = parts[0]
name = parts[1]
price = int(parts[2])
outer_dict[type][name] = price # add `name` to the `type` dict as a new key
uj5u.com熱心網友回復:
對于outer_dict,您可以使用defaultdictfrom collections,使其{}成為默認值。這樣你就可以簡單地outer_dict[type][name] = price為每一行做
uj5u.com熱心網友回復:
謝謝大家的幫助。我忘了提及,我不允許使用內置函式,但您的建議仍然是有用的,可能對其他在 samillair 問題上苦苦掙扎的人有用。我通過使用更新方法讓代碼以一種想要的方式作業,建議:TheFlyingObject
這是固定的內部 for 回圈,它的作業原理是這樣的:
inner_dict = {}
# Adding each name and price to the inner dictionaries.
for i in range(1, len(parts)):
inner_dict[name] = price
# Adding the created inner dict into the outer dictionary if it's
# not already there.
if type not in outer_dict:
outer_dict[type] = inner_dict
# If there is already an outer dict existing, updating the inner dict.
else:
outer_dict[type].update(inner_dict)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/366694.html
上一篇:從字典創建資料幀時出現StopIteration錯誤
下一篇:字典的深度復制值到變數c#
