Mostafa Mohamed Mostafa Mohamed - 1 year ago 79
Python Question

How to manipulate list of list of dictionaries

Hi there i have a wired situation here that i want to manipulate a dictionary key value which is list of lists include dictionaries here is the formation of the data i have

my_list=[{'data': [[{'name': [0.0, 0.0]}], [{'name': [False, False]}], [{'name': [u'xm', u'xc']}]],'name': u'new',}]

what i want to do is to convert this to :

my_list=[{'data': [[{'name': 0.0},{'name': 0.0}], [{'name': False},{'name': False}], [{'name': u'xm'},{'name': u'xc'}]],'name': u'new',}]

what i have tried so far is :

new_lists = []
for new in x[0]['data']:
for new_list in new:
for g in new_list['name']:
new_list['name'][new_list['name'].index(g)] = {'name': g}
for stay in x[0]['data']:

could i have some help here ?

Answer Source

Here we go, a version independant from keys value :

my_list=[{'data': [[{'foo': [0.0, 0.0]}], [{'bar': [False, False]}], [{'pop': [u'xm', u'xc']}]]}]

buff = []
for elt in my_list[0]['data']:
    a = []
    k = elt[0].keys()[0]
    val = elt[0][k]
    for i in val:
        a.append({k: i})

output = [{'data': buff}]

Results :

[{'data': [[{'foo': 0.0}, {'foo': 0.0}], [{'bar': False}, {'bar': False}], [{'pop': u'xm'}, {'pop': u'xc'}]]}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download