简体   繁体   中英

Python convert a list to a specific dict

I have a list and I want to convert to a specific dict dict_a

Input :

a = ['AAA: key1', 'value1', 'value2', 'AAA: key2', 'value3', 'value4', 'value5', 'AAA: key3', 'value6', 'value7']

Output expected :

dict_a = {'key1': [value1, value2], 'key2': [value3, value4, value5], 'key3': [value6, value7]}

My attempt :

for elem in a:
    if a.startswith(AAA:):
        d_a = {elem}

This is one way using collections.defaultdict :

from collections import defaultdict

a = ['AAA: key1', '  value1', '  value2', 'AAA: key2', '  value3', '  value4', '  value5', 'AAA: key3', '  value6', '  value7']

d = defaultdict(list)
for x in a:
    if not x.startswith('AAA'):
        d[c].append(x.strip())
    else:
        c = x.split(': ')[1]

print(d)
# defaultdict(<class 'list'>, {'key1': ['value1', 'value2'], 'key2': ['value3', 'value4', 'value5'], 'key3': ['value6', 'value7']})

I like to use a generator for problems like this, accumulating a result unitl we see the next result start, then yielding the result we've collected.

def key_val_gen(a):
    key = None
    vals = []
    for item in a:
        if item.startswith('AAA: '):
            if key:
                yield key, vals
            key  = item.split(maxsplit=1)[1]
            vals = []
        else:
            vals.append(item)
    if key:
        yield key, vals

a = ['AAA: key1', 'value1', 'value2', 'AAA: key2', 'value3', 'value4', 'value5', 'AAA: key3', 'value6', 'value7']

print(dict(key_val_gen(a)))
# {'key1': ['value1', 'value2'], 'key2': ['value3', 'value4', 'value5'], 'key3': ['value6', 'value7']}
from collections import defaultdict

result = defaultdict(list)
key = None
a = ['AAA: key1', '  value1', '  value2', 'AAA: key2', '  value3', '  value4', ' value5', 'AAA: key3', '  value6', '  value7']

for elem in a:
    if elem.startswith('AAA:'):
        key = elem.split(':')[1].strip()
    elif key:
        result[key].append(elem.strip())

print(result)

You could also use itertools.groupby to group items in "is a key" and "is a value" and then combine consecutive elements by using next on the same iterator:

>>> from itertools import groupby
>>> groups = (next(g).lstrip("AAA: ") if k else list(g)
...           for k, g in groupby(a, key=lambda x: x.startswith("AAA: ")))
...
>>> {g: next(groups) for g in groups}
{'key1': ['value1', 'value2'],
 'key2': ['value3', 'value4', 'value5'],
 'key3': ['value6', 'value7']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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