'convert a list of objects to a list of single lists
I have a question: I have a list of nested objects that I managed to change it to this format:
converted_nested_list = [
{"cmd_count": 2, "name": "jacky", "powered": 10},
{"cmd_count": 9, "name": "madi", "powered": 26},
{"cmd_count": 7, "name": "alisson", "powered": 77},
]
if you can just explain to me how can I converted to this format in a pythonic way:
wanted_format = {
"person_names": ["jacky","madi","alisson"],
"person_details":[
{"label":"cmd_count", "stats":[2,9,7]},
{"label":"powered","stats":[10,26,77]}
]
}
Solution 1:[1]
Using list comprehension:
wanted_format = {
'person_names': [person['name'] for person in converted_nested_list],
'person_details': [
{'label': 'cmd_count', 'stats': [person['cmd_count'] for person in converted_nested_list]},
{'label': 'powered', 'stats': [person['powered'] for person in converted_nested_list]}
]
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MikeM |
