Create a dictionary from a list

1

I have the following list:

msg = ['CAD400','Uma Filial...','Solucao:','O campo...','','LIB310','A Filial...','Solucao:','Foi identificado...','Foi corrigido...','','PAG302','Mudanca...','Solucao:','O erro...','O programa...','Programa alterado...']

I want a dictionary with list data as follows:

msg_nova = {'CAD_001': ['Uma Filial...','Solucao:','O campo...'],'REC_002': ['A Filial...','Solucao:','Foi identificado...','Foi corrigido...'],'PAG_003': ['Mudanca...','Solucao:','O erro...','O programa...','Programa alterado...']}

I have already tried several ways and I have not been able to make the descriptions of each program (CAD, REC, PAG) linked to each one. I even managed to create the keys but the descriptions are each separated into a list.

    
asked by anonymous 18.10.2017 / 04:41

1 answer

3

You can scan the list by scanning items prefixed with CAD , PAG or LIB . If the item has any of the prefixes, a new key is included in a dictionary and its value (a list) is filled in until a new key is found.

Here's a possible solution:

msg = [ 'CAD400','Uma Filial...','Solucao','O campo...','','LIB310','A Filial...','Solucao','Foi identificado...','Foi corrigido...','','PAG302','Mudanca...','Solucao','O erro...','O programa...','Programa alterado...']

prfx = ['CAD','PAG','LIB']
dic = {}
key = ''

for m in msg:
    for p in prfx:
        if p in m:
            key = m
            dic[key] = []
            break
    if m != key:
        dic[key].append(m)

print(dic)

Output:

{'LIB310': ['A Filial...', 'Solucao', 'Foi identificado...', 'Foi corrigido...', ''],
 'PAG302': ['Mudanca...', 'Solucao', 'O erro...', 'O programa...', 'Programa alterado...'],
 'CAD400': ['Uma Filial...', 'Solucao', 'O campo...', '']}
    
18.10.2017 / 12:43