【发布时间】:2016-02-05 08:22:03
【问题描述】:
我对我遇到的这个特殊问题有点困惑。我有一个可行的解决方案,但我认为它不是 Pythonic。
我有一个这样的原始文本输出:
Key 1
Value 1
Key 2
Value 2
Key 3
Value 3a
Value 3b
Value 3c
Key 4
Value 4a
Value 4b
我正在尝试制作字典:
{ 'Key 1': ['Value 1'], 'Key 2': ['Value 2'], 'Key 3': ['Value 3a', 'Value 3b', 'Value 3c'], 'Key 4': ['Value 4a', 'Value 4b'] }
原始输出可以变成一个字符串,它看起来像这样:
my_str = "
Key 1\n\tValue 1
\nKey 2\n\tValue 2
\nKey 3\n\tValue 3a \n\tValue 3b \n\tValue 3c
\nKey 4\n\tValue 4a \n\tValue 4b "
所以 Values 由 \n\t 分隔,而 Keys 由 \n 分隔
如果我尝试做这样的事情:
dict(item.split('\n\t') for item in my_str.split('\n'))
它没有正确解析它,因为它也在 \n\t 中拆分了“n”。
到目前为止,我有这样的事情:
#!/usr/bin/env python
str = "Key 1\n\tValue 1\nKey 2\n\tValue 2\nKey 3\n\tValue 3a \n\tValue 3b \n\tValue 3c\nKey 4\n\tValue 4a \n\tValue 4b"
output = str.replace('\n\t', ',').replace('\n',';')
result = {}
for key in output.split(';'):
result[key.split(',')[0]] = key.split(',')[1:]
print result
返回:
{'Key 1': ['Value 1'], 'Key 2': ['Value 2'], 'Key 3': ['Value 3a ', 'Value 3b ', 'Value 3c'], 'Key 4': ['Value 4a ', 'Value 4b']}
但是,这对我来说看起来很恶心,我只是想知道是否有一种 Python 的方式来做到这一点。任何帮助将不胜感激!
【问题讨论】:
-
我看到你现在自己找到了它。你现在问它是“Pythonic”。它有效吗?如果是这样,那么,谁在乎呢?
标签: python string dictionary split