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

时间:2020-10-24 20:43:14

标签: python

我打开一个文件,其中每一行代表一个学生的信息。 像这样存储:

41097-xxkx:Johansson Elin:TE20:290

每个值都用":"分隔的地方。下一行是新学生,依此类推。

通过这个,我将把值添加到字典中,这样每个学生都会得到“ 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)

2 个答案:

答案 0 :(得分:1)

挺直的

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)

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

例如,在字符"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”

答案 1 :(得分:1)

您需要在冒号上分割行,然后使用上面为每行列出的键来构建字典。

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)))