[英]Convert text file to dictionary with one key and multiple values
我正在嘗試使用defaultdict
將文本文件轉換為字典。
輸出良好且預期。 但是,我現在關心的是,如果我的txt文件格式不僅是“:”而且還包含“,”和“(spacing)”,該如何進一步拆分值? 我嘗試在其中插入更多的循環,但沒有成功,因此我將其刪除。
例如:
Cost : 45
Shape: Square, triangle, rectangle
Color:
red
blue
yellow
所需的輸出:
{'Cost' ['45']}
{'Shape' ['Square'], ['triangle'], ['rectangle'] }
{'Color' ['red'], ['blue'], ['yellow']}
這是我當前的代碼。 我應該如何修改?
#converting txt file to dictionary with key value pair
from collections import defaultdict
d = defaultdict(list)
with open("t.txt") as fin:
for line in fin:
k, v = line.strip().split(":")
d[k].append(v)
print d
當找到帶有:
的行時,您有一個鍵,否則就有值,因此將值添加到最后一個鍵k
:
from collections import defaultdict
d = defaultdict(list)
with open("test.txt") as fin:
for line in fin:
if ":" in line:
k, v = line.rstrip().split(":")
d[k].extend(map(str.strip,v.split(",")) if v.strip() else [])
else:
d[k].append(line.rstrip())
print(d)
進出:
Cost : 45
Shape: Square, triangle, rectangle
Color:
red
blue
yellow
Foo : 1, 2, 3
Bar :
100
200
300
輸出:
from pprint import pprint as pp
pp(d)
{'Bar ': ['100', '200', '300'],
'Color': ['red', 'blue', 'yellow'],
'Cost ': ['45'],
'Foo ': ['1', '2', '3'],
'Shape': ['Square', 'triangle', 'rectangle']}
您可以輕松地更改代碼,以將每個值放在一個單獨的列表中,但我認為將所有值放在一個列表中會更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.