[英]Reading a txt file into a dictionary
我有一個像這樣的文本文件:
Ben
5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5
Moose
5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0
Reuven
5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3
我需要將此 txt 文件轉換為字典,其中每隔一行是它后面的行的鍵。 例子:
d = {'ben': 5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5,
"moose":5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0,
"Reuven":5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3}
你可以通過以下方式得到你想要的
這是如何工作的
enumerate
為您提供每次迭代的 (index, value) 對,您可以使用文件 object f
直接遍歷文件中的每一行。 通過這種方式,如果您擔心的話,您無需將整個文件讀入您的 memory。
i % 2 == 0
表示該行是偶數行,因此將成為字典中的鍵。 然后 else 部分將使用此鍵添加奇數行。
如果您不想在此處列出列表,則可以將line.strip().split()
更改為僅line
。
f = open('file.txt')
res = {}
for i, line in enumerate(f):
if i % 2 == 0:
key = line.strip()
else:
res[key] = line.strip().split()
print(res)
f.close()
Output
{'Ben': ['5', '0', '0', '0', '0', '0', '0', '1', '0', '1', '-3', '5', '0', '0', '0', '5', '5', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '0', '0', '1', '3', '0', '1', '0', '-5', '0', '0', '5', '5', '0', '5', '5', '5', '0', '5', '5', '0', '0', '0', '5', '5', '5', '5', '-5'], 'Moose': ['5', '5', '0', '0', '0', '0', '3', '0', '0', '1', '0', '5', '3', '0', '5', '0', '3', '3', '5', '0', '0', '0', '0', '0', '5', '0', '0', '0', '0', '0', '3', '5', '0', '0', '0', '0', '0', '5', '-3', '0', '0', '0', '5', '0', '0', '0', '0', '0', '0', '5', '5', '0', '3', '0', '0'], 'Reuven': ['5', '-5', '0', '0', '0', '0', '-3', '-5', '0', '1', '-5', '5', '0', '1', '0', '1', '-3', '1', '-5', '0', '0', '0', '0', '0', '0', '3', '0', '0', '0', '0', '-5', '1', '0', '1', '0', '-5', '0', '3', '-3', '3', '0', '1', '5', '1', '0', '0', '0', '0', '0', '1', '3', '1', '5', '1', '3']}
代碼
with open('input.txt', 'r') as infile:
data = infile.readlines() # data is a list with lines of file
# Use slicing and zip with dictionary comprehension
# data[::2] are even lines of data
# data[1::2] are odd lines of data
# use rstrip to get rid of trailing '\n'
result = {x.rstrip():y.rstrip() for x, y in zip(data[0::2], data[1::2])}
結果包含
{'Ben': '5 0 0 0 0 0 0 1 0 1 -3 5 0 0 0 5 5 0 0 0 0 5 0 0 0 0 0 0 0 0 1 3 0 1 0 -5 0 0 5 5 0 5 5 5 0 5 5 0 0 0 5 5 5 5 -5',
'Moose': '5 5 0 0 0 0 3 0 0 1 0 5 3 0 5 0 3 3 5 0 0 0 0 0 5 0 0 0 0 0 3 5 0 0 0 0 0 5 -3 0 0 0 5 0 0 0 0 0 0 5 5 0 3 0 0',
'Reuven': '5 -5 0 0 0 0 -3 -5 0 1 -5 5 0 1 0 1 -3 1 -5 0 0 0 0 0 0 3 0 0 0 0 -5 1 0 1 0 -5 0 3 -3 3 0 1 5 1 0 0 0 0 0 1 3 1 5 1 3'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.