繁体   English   中英

使用一个键和多个值将文本文件转换为字典

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM