Python 将文本文件转换为具有一个键和多个值的字典

Python 将文本文件转换为具有一个键和多个值的字典,python,python-2.7,Python,Python 2.7,我正在尝试将一个文本文件转换为字典,我可以使用defaultdict来实现 产出良好,符合预期。但我现在关心的是,如果我的txt文件格式不仅是“:”而且还有“,”和“(空格)”,如何进一步分割我的值?我尝试插入更多的循环,但没有成功,所以我删除了它们 例如: Cost : 45 Shape: Square, triangle, rectangle Color: red blue yellow 期望输出: {'Cost' ['45']} {'Shape' ['Square'], ['tr

我正在尝试将一个文本文件转换为字典,我可以使用
defaultdict
来实现

产出良好,符合预期。但我现在关心的是,如果我的txt文件格式不仅是“:”而且还有“,”和“(空格)”,如何进一步分割我的值?我尝试插入更多的循环,但没有成功,所以我删除了它们

例如:

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)
Inout:

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']}

您可以轻松地更改代码,将每个值放在一个单独的列表中,但我认为一个列表中的所有值都更有意义

@martin Pieters编辑。Tks!我懂了!我已经试了好几个小时了。你真棒!谢谢