从文本文件中读取值,然后将每个值添加到附加到列表的dict中

2024-09-27 09:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我打开一个文件,其中每行代表一个学生的信息。 存储方式如下:

41097-xxkx:Johansson Elin:TE20:290

每个值都用":"分隔,下一行是new student,依此类推

通过这个,我将把这些值加到一个dict中,这样每个学生都会得到一个dict“prsnummer”,“namn”等等。然后,这些指令将存储在一个列表中

# How I think about dealing with it.
# Tho stripping every part, and adding to dict was harder.

with open("text.txt", "r") as f:
    for line in f:
        """
        Do something
        """  

# How txt files look like. Each value is seperated with a :
# 040512-xxkx:Valek Kevin:TE20:280
# 041097-xxkx:Johansson Elin:TE20:290

# In the end it will look like:
list_of_dicts = [
{"prsnummer" : "040512-xxkx", "namn" : "Valek Kevin", "Klass" : "TE20", "Merit" : "280"},
{"prsnummer" : "041097-xxkx", "namn" : "Johansson Elin", "Klass" : "TE20", "Merit" : "290"}
]

# (Merit is meant to be stored as a str)

Tags: totxtaswithit学生dicthow
2条回答

这是相当大的进步

list_of_dicts = []
with open("text.txt", "r") as f:
    curr_dict = {}
    for line in f:
        values = line.split(":") 
        curr_dict["prsnummer"] = values[0]
        curr_dict["namn"] = values[1]
        curr_dict["Klass"] = values[2]
        curr_dict["Merit"] = values[3]
    list_of_dicts.append(curr_dict)

基本上,您可以解析行,将字符串拆分为“:”字符,然后根据列表位置提取信息

例如,在char":"上拆分字符串"040512-xxkx:Valek Kevin:TE20:280",将生成这个values列表

values = line.split(":")
# ["040512-xxkx", "Valek Kevin", "TE20", "280"]
  • 在位置0(值[0])中有字符串“040512 xxkx”
  • 在位置1(值[1])中有字符串“Valek Kevin”
  • 在位置2(值[2])中有字符串“TE20”
  • 在位置2(值[3])中有字符串“280”

您需要拆分冒号上的行,然后使用上面为每行列出的键构造一个字典

with open("text.txt", "r") as f:
    list_of_dicts = []
    keys = ["prsnummer", "namn", "Klass", "Merit"]
    for line in f:
        values = line.split(':')
        list_of_dicts.append(dict(zip(keys, values)))

相关问题 更多 >

    热门问题