在Python中将逗号分隔的项添加到dict中

2024-04-20 16:03:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是python2.7和pythondicts

我的输出是这样的:

goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12

我的代码:

    d = {}
    for line in output.split("\n"):
        if ":" not in line:
            continue
        key, value = line.strip().split(":", 1)
        d[key] = value

期望的键及其值:

 trunk_names: trunk01, trunk02, trunk03,trunk04,trunk05,trunk06, trunk07,trunk08,trunk09,trunk10, trunk11,trunk12

正在输出的实际键和值:

 trunk_names: trunk01, trunk02, trunk03,trunk04,

Tags: nameslinetrunktrunk07trunk10trunk08trunk06trunk01
2条回答

您的结构有多稳定,如果它非常稳定并且数据质量很高,那么您可以通过测试line.endswith(',')来简化:

In []:
d = {}
f = iter(output.split('\n'))
for line in f:
    key, line = map(str.strip, line.split(':', 1))
    while line.endswith(','):
        line += next(f)
    d[key] = [i.strip() for i in line.split(',')]

pprint.pprint(d)

Out[]:
{'goods': ['apples', 'oranges'],
 'trunk_names': ['trunk01',
                 'trunk02',
                 'trunk03',
                 'trunk04',
                 'trunk05',
                 'trunk06',
                 'trunk07',
                 'trunk08',
                 'trunk09',
                 'trunk10',
                 'trunk11',
                 'trunk12']}
from collections import defaultdict

output = '''
goods: apples, oranges
trunk_names: trunk01, trunk02, trunk03,trunk04,
             trunk05,trunk06, trunk07,trunk08,
             trunk09,trunk10, trunk11,trunk12
'''

d = defaultdict(list)

current_key = None

for line in output.split('\n')[1:]:
    if ":" in line:
        current_key = line.split(':')[0].strip()
        values = line.split(':')[1]
    else:
        values = line

    d[current_key] += [
        value.strip()
        for value in values.split(',')
        if value.strip()
    ]


print(d)

提供:

defaultdict(<type 'list'>, {'trunk_names': ['trunk01', 'trunk02', 'trunk03', 'trunk04', 'trunk05', 'trunk06', 'trunk07', 'trunk08', 'trunk09', 'trunk10', 'trunk11', 'trunk12'], 'goods': ['apples', 'oranges']})

相关问题 更多 >