[英]how to read txt file data and convert into nested dictionary in python
I have this txt file but I'm having trouble in converting it into a nested dictionary in python.我有这个 txt 文件,但在将其转换为 python 中的嵌套字典时遇到了麻烦。 The txt file only has the values of the pokemon but are missing the keys such as 'quantity' or 'fee'.
txt 文件只有口袋妖怪的值,但缺少诸如“数量”或“费用”之类的键。 Below is the content in the txt file.
下面是txt文件中的内容。 (I have the ability to change the txt file if needed)
(如果需要,我可以更改 txt 文件)
charmander,3,100,fire
squirtle,2,50,water
bulbasaur,5,25,grass
gyrados,1,1000,water flying
This is my desired dictionary:这是我想要的字典:
pokemon = {
'charmander':{'quantity':3,'fee':100,'powers':['fire']},
'squirtle':{'quantity':2,'fee':50,'powers':['water']},
'bulbasaur':{'quantity':5,'fee':25,'powers':['grass']},
'gyrados':{'quantity':1,'fee':1000,'powers':['water','flying']}
}
Need some guidance here, any help is appreciated:)这里需要一些指导,任何帮助表示赞赏:)
Convert text file to lines, then process each line using "," delimiters.将文本文件转换为行,然后使用“,”分隔符处理每一行。 For powers, split the string again using " " delimiter.
对于幂,使用“”分隔符再次拆分字符串。 Then just package each extracted piece of information into your dict structure as below.
然后只需 package 每个提取的信息到您的 dict 结构中,如下所示。
with open('pokemonInfo.txt') as f:
data = f.readlines()
dict = {}
for r in data:
fields = r.split(",")
pName = fields[0]
qty = fields[1]
fee = fields[2]
powers = fields[3]
dict[pName] = {"quantity": qty, "fee": fee, "powers": [p.strip() for p in powers.split(" ")]}
for record in dict.items():
print(record)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.