I do have a dynamic text that will change. I want to store those values in a meaningful way. I have created a nested list to store them but I need to convert those to individual dictionaries and store it into a list. How do I do this?
str1 = "<RT-AC5300>192.168.1.1>34:97:F1:3B:AA:24>1<Lyra>192.168.1.129>10:7B:4B:36:A1:15>0<Lyra>192.168.1.207>10:7B:43:C7:A0:13>0<Lyra>192.168.1.195>10:7B:44:AA:BE:1B>0" value = str1.replace('<',' ').replace('>',' ').lstrip().split(' ') keys = ['device','ip','mac','stat'] devices = [value[x:x+4] for x in range(0, len(value), 4)]
So far good. Devices variable is a nested list.
[['RT-AC5300', '192.168.1.1', '34:97:F1:3B:AA:24', '1'], ['Lyra', '192.168.1.129', '10:7B:4B:36:A1:15', '0'], ['Lyra', '192.168.1.207', '10:7B:43:C7:A0:13', '0'], ['Lyra', '192.168.1.195', '10:7B:44:AA:BE:1B', '0']]
I need to convert it so that it gives this:
[{'device': 'RT-AC5300', 'ip': '192.168.1.1', 'mac': '34:97:F1:3B:AA:24', 'stat': '1'}, {'device': 'Lyra', 'ip': '192.168.1.129', 'mac': '10:7B:4B:36:A1:15', 'stat': '0'}, {'device': 'Lyra', 'ip': '192.168.1.207', 'mac': '10:7B:43:C7:A0:13', 'stat': '0'}, {'device': 'Lyra', 'ip': '192.168.1.195', 'mac': '10:7B:44:AA:BE:1B', 'stat': '0'}]
I can manually do this like below but it will not work since the length may vary so it needs to be iterated.
ss = [ dict(zip(keys, devices[0])), dict(zip(keys, devices[1])), dict(zip(keys, devices[2])), dict(zip(keys, devices[3])) ]
I tried
for x in enumerate(devices): ai[x] = dict(zip(keys, devices[x]))
but it gives error.
Advertisement
Answer
Simply:
ai = [dict(zip(keys, device)) for device in devices]