我对我遇到的这个特殊问题有点困惑。我有一个可行的解决方案,但我认为它不是很 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']}
但是,这对我来说看起来很恶心,我只是想知道是否有 pythonic 方法可以做到这一点。任何帮助将不胜感激!
请您参考如下方法:
包含电池 - defaultdict 将新键的值作为列表自动混合,我们利用 str 的 iswhitespace 方法来检查缩进(否则我们可以使用正则表达式):
from collections import defaultdict
data = """
Key 1
Value 1
Key 2
Value 2
Key 3
Value 3a
Value 3b
Value 3c
Key 4
Value 4a
Value 4b
"""
result = defaultdict(list)
current_key = None
for line in data.splitlines():
if not line: continue # Filter out blank lines
# If the line is not indented then it is a key
# Save it and move on
if not line[0].isspace():
current_key = line.strip()
continue
# Otherwise, add the value
# (minus leading and trailing whitespace)
# to our results
result[current_key].append(line.strip())
# result is now a defaultdict
defaultdict(<class 'list'>,
{'Key 1': ['Value 1'],
'Key 2': ['Value 2'],
'Key 3': ['Value 3a', 'Value 3b', 'Value 3c'],
'Key 4': ['Value 4a', 'Value 4b']})
