Reemplacing a list into a dictionary by another dictionary

Viewed 20

I have a dictionary with some values that are type list, i need to convert each list in another dictionary and insert this new dictionary at the place of the list.

Basically, I have this dictionary

Dic = {

'name': 'P1', 
'srcintf': 'IntA', 
'dstintf': 'IntB', 
'srcaddr': 'IP1', 
'dstaddr': ['IP2', 'IP3', 'IP4'], 
'service': ['P_9100', 'SNMP'],
'schedule' : 'always',
}

I need to reemplace the values that are lists Expected output:

Dic = {

'name': 'P1', 
'srcintf': 'IntA', 
'dstintf': 'IntB', 
'srcaddr': 'IP1', 
'dstaddr': [
          {'name': 'IP2'}, 
          {'name': 'IP3'}, 
          {'name': 'IP4'}
          ],
'service': [
          {'name': 'P_9100'},
          {'name': 'SNMP'}
          ],
'schedule' : 'always',
}

So far I have come up with this code:

for k,v in Dic.items():
     if not isinstance(v, list):
          NewDic = [k,v]
          print(NewDic)
     else:
          values = v
          keys = ["name"]*len(values)
          for item in range(len(values)):
               key = keys[item]
               value = values[item]
               SmallDic = {key : value}
               liste.append(SmallDic)
               NewDic = [k,liste]

which print this

['name', 'P1']
['srcintf', 'IntA']
['dstintf', 'IntB']
['srcaddr', 'IP1']
['schedule', 'always']
['schedule', 'always']

I think is a problem with the loop for, but so far I haven't been able to figure it out.

1 Answers

You need to re-create the dictionary. With some modifications to your existing code so that it generates a new dictionary & fixing the else clause:

NewDic = {}
for k, v in Dic.items():
    if not isinstance(v, list):
        NewDic[k] = v
    else:
        NewDic[k] = [
            {"name": e} for e in v  # loop through the list values & generate a dict for each
        ]

print(NewDic)

Result:

{'name': 'P1', 'srcintf': 'IntA', 'dstintf': 'IntB', 'srcaddr': 'IP1', 'dstaddr': [{'name': 'IP2'}, {'name': 'IP3'}, {'name': 'IP4'}], 'service': [{'name': 'P_9100'}, {'name': 'SNMP'}], 'schedule': 'always'}

Related