1 python dictionary nested filereader data-structures
我在使用 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
Run Code Online (Sandbox Code Playgroud)
我想要实现的是,我尝试为每个组件类型 {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}
Run Code Online (Sandbox Code Playgroud)
但相反,它看起来像这样:
"GPU": {"GeForce GTX 2060 2": 233},
"CPU": {"Intel Core i7-11700 : 360},
"RAM": {"HyperX 16GB": 180},
"PSU": {"Corsair RM850X": 210}
Run Code Online (Sandbox Code Playgroud)
问题是:我无法正确创建字典,因为新的内部键和值会相互覆盖。我怎样才能使这个循环不这样做,而是只是在内部字典中逐个添加新值?
这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
提前感谢大家的帮助。确实是需要的!
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)
Run Code Online (Sandbox Code Playgroud)
输出:
>>> 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'}}
Run Code Online (Sandbox Code Playgroud)
with open('file.txt') as f:
for line in f:
# rest of the loop from above
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16781 次 |
| 最近记录: |