你如何在python中输入文本文件到字典?

时间:2016-11-16 17:56:52

标签: python-3.x

我是python的新手,我试图查找它,但我仍然不确定你是怎么做的。

现在我的文本文件如下所示:

'a':bla bla bla
'b':bla bla bla
'c':bla bla bla

我希望将此文件读入字典,以便第1列是键,第2列是值,即:

d = {'a':bla bla bla, 'b':bla bla bla, 'c':bla bla bla}

1 个答案:

答案 0 :(得分:1)

python3中的手动方法:

a_dict = {}  # To store the values in
with open('file.txt') as input_file:
    for line in input_file:
        entry = line.split(":")  # split for key, value
        # store into dict, need to strip ' from the key and \n from value
        a_dict[entry[0].strip("' ")] = entry[1].strip()

print(a_dict)  # Show the results