简体   繁体   English

如何在 python 中读取 txt 文件数据并转换成嵌套字典

[英]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 文件)

pokemon info口袋妖怪信息

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.

相关问题 读取txt文件数据作为字典 - Read txt file data as dictionary 如何从 txt 文件中读取值是嵌套字典并且嵌套字典的键由我给出的字典? - How to read from a txt file into a dictionary where the value is a nested dictionary and the key of the nested dictionary is given by me? 如何将数据转换为 python、dataframe 中的嵌套字典 - how to convert data into nested dictionary in python,dataframe 将 read.txt 文件转换为可操作的字符串以转换为字典 - read .txt file into a manipulatable string to convert into dictionary 如何读取文件的内容并将其转换为python中的字典 - how to read the contents of file and convert it into dictionary in python 如何将 txt 文件中的行分组到嵌套字典(Python) - How to group the line in txt file to nested dictionary (Python) 如何使用邻接表python阅读txt文件并创建字典 - How to read txt file and create dictionary with adjacency list python Python-如何将 .txt 文件中的行转换为字典元素? - Python- how to convert lines in a .txt file to dictionary elements? 如何将字典格式的txt文件转换为python中的数据帧? - How to convert a txt file with dictionary format to dataframe in python? Python-如何将.txt文件(两列)转换为字典元素? - Python- how to convert .txt file (two columns) to dictionary elements?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM