user2955338 user2955338 - 1 year ago 63
Python Question

How to collate attribute values stored as dicts within a list?

In my list each element is a dict of the form

ID: attribute_value
. Each dict holds the attribute value for a different attribute (e.g. name or age). An example is below:

list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',},
{'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}]

I want to manipulate this list so that the dicts contain all the attributes for a particular ID. The ID itself must form part of the resulting dict. An example output is shown below:

list_2 = [{'id' : '1', 'name' : 'name_1', 'age': 'age_1'},
{'id' : '2', 'name' : 'name_2', 'age': 'age_2'},
{'id' : '3', 'name' : 'name_3', 'age': 'age_3'}]

Can anyone propose a solution to this problem?

Answer Source
In [1]: list_1 = [{'1': 'name_1', '2': 'name_2', '3': 'name_3',}, 
   ...:            {'1': 'age_1', '2': 'age_2' ,'3': 'age_3',}]

In [2]: def foo(id):
   ...:     name = list_1[0][id]
   ...:     age = list_1[1][id]
   ...:     return locals()

In [4]: [foo(x) for x in list_1[0].keys()]
[{'age': 'age_1', 'id': '1', 'name': 'name_1'},
 {'age': 'age_3', 'id': '3', 'name': 'name_3'},
 {'age': 'age_2', 'id': '2', 'name': 'name_2'}]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download