Home > OS >  Constructing a list of dictionaries
Constructing a list of dictionaries

Time:04-20

I have data in this format;

my_dict = {
'data1':[
{'age':32,'height':43,'weight':67},
{'age':21,'height':33,'weight':34}
],
'data2':[
{'name':'james','department':'web'},
{'name':'Joe','department':'social'}
]
}

I want to get age, weight, and name. How can I construct a list of dictionaries of all records? e.g)

data = [{'age':32,'weight':43,'name':'james'},{'age':32,'weight':33,'name':'joe'}]

Any help will be appreciated.

CodePudding user response:

There are many ways you can do this. One easy to understand method is to do a for loop with a zip iterator:

data = []

for data1, data2 in zip(my_dict.get('data1'), my_dict.get('data2')):
    data.append({'age':data1.get('age'),
                 'weight':data1.get('weight'),
                 'name':data2.get('name')})

CodePudding user response:

This is one way to do what you want. We make data a list of empty dicts and then based on the index of a dict within one of the data lists, we update the corresponding dict in the data list.

# list of empty dicts
data = [{} for i in range(2)]
# holds what info we want
select = {'age', 'weight', 'name'}
for k in my_dict:
    for idx, i in enumerate(my_dict[k]):
        data[idx].update({k: v for k, v in i.items() if k in select})

print(data)

Output

[{'age': 32, 'name': 'james', 'weight': 67},
 {'age': 21, 'name': 'Joe', 'weight': 34}]
  • Related