Python:如何将文本文件中的数据转换为字典?

时间:2015-09-17 19:45:32

标签: python

Python:如何将文本文件中的数据转换为字典? 我的文本文件中有数据行,即:name = score 我如何将这些信息转换成字典? 标题说明了一切。请帮帮我。

with open(filepath, 'r') as file:
    list = []
    for line in file:
        list.append(line[1:-1].split(","))

我的输入格式:

Kik = 4
Lolol = 3
Kiko = 8 
Darkling = 1 
Johnny = 10

2 个答案:

答案 0 :(得分:1)

如果你有文件

name1 = value1

name2 = value2

name3 = value3

name4 = value4

import re

d = {}

with open('data', 'r') as f:

    for line in f:

        line =   re.sub('\s', '', line)

        key, value = line.split('=')

        d[key] = value

for el in d.items():

    print(el)

(' name1',' value1')

(' name4',' value4')

(' name2',' value2')

(' name3',' value3')

答案 1 :(得分:0)

你只需要拆分和剥离:

with open("test.txt") as f:
    scores_dct = {name.strip(): sco.strip() for line in f 
                  for name, sco in (line.split("="),)}
print(scores_dct)
'Kik': '4', 'Lolol': '3', 'Kiko': '8', 'Darkling': '1', 'Johnny': '10'}

dict使用map

with open("test.txt") as f:
    scores_dct = dict(map(str.strip,line.split("=")) for line in f)
    print(scores_dct)
{'Kik': '4', 'Lolol': '3', 'Kiko': '8', 'Darkling': '1', 'Johnny': '10'}
相关问题