我有一個外部文件中下面的文字Python的文本詞典
A#
M*
Y%
,並想將其讀入一本字典,以便它讀成
Dictionary = {'A': '#', 'M': '*', 'Y': '%'}
我可以閱讀文本文件,如果它在字母和符號之間有一個逗號,但不能沒有。有沒有人有任何想法?
我有一個外部文件中下面的文字Python的文本詞典
A#
M*
Y%
,並想將其讀入一本字典,以便它讀成
Dictionary = {'A': '#', 'M': '*', 'Y': '%'}
我可以閱讀文本文件,如果它在字母和符號之間有一個逗號,但不能沒有。有沒有人有任何想法?
只是非常簡單。當你迭代每一行時,你需要每行的第一個字符 - 這是字母 - 第二個字符 - 這是符號)來填充你的字典。
dictionary = {}
with open('filename') as f:
for line in f:
dictionary[line[0]] = line[1]
謝謝你,我正在做一些愚蠢的錯誤。 – MrC
你可以做一個詞典理解。
with open('somefile') as file:
output = {line[0] : line[1] for line in file}
>>> s ='''A#
M*
Y%'''
>>> dict(zip(*line)[0] for line in s.splitlines())
{'A': '#', 'Y': '%', 'M': '*'}
如果你從文件中讀取:
>>> with open('foo.txt') as f:
print dict(zip(*line.rstrip())[0] for line in f)
...
{'A': '#', 'Y': '%', 'M': '*'}
dict(map(str.strip, open("filename")))
我會去:
with open('yourfile') as fin:
mydict = dict(line.rstrip() for line in fin)
這依賴於一個事實,即dict
需要一個2項來構建鍵/值對,並通過刪除trai從每行的空白,然後我們應該結束與2項目。
這樣做的優點是,它更在原子施工期間拋出的異常意味着dict
不會保持部分填充,而你只需要處理一個例外,而不是IndexError
S或其他人,可能是拋出使用字典/補充/等...
這兩個符號都在一個新的行,作爲編輯顯示? – doctorlove
@doctorlove看看原文;它只是沒有縮進。 – poke