将外部文件中的字符添加到字典中

时间:2014-03-11 19:32:29

标签: python dictionary updating

在python中,我如何从包含以下内容的txt文档中选择单个字符:

A#

M *

N%

(在单独的行上)...然后用字母作为键,符号作为值更新字典。

我最接近的是:

ftwo = open ("clues.txt", "r")
for lines in ftwo.readlines():
    for char in lines:

我对编码很新,所以不能解决它!

2 个答案:

答案 0 :(得分:0)

假设每行包含两个字符(首先是键,然后是值):

with open('clues.txt', 'r') as f:
    myDict = {a[0]: a[1] for a in f}

如果输入文件中有空行,则可以将其过滤掉:

with open('clues.txt', 'r') as f:
    myDict = {a[0]: a[1] for a in f if a.strip()}

答案 1 :(得分:0)

首先,您希望一次读取每一行:

my_dict = {}
with open ("clues.txt", "r") as ftwo:
    for line in ftwo:
        # Then, you'll want to put your elements in a dict
        my_dict[line[0]] = line[1]