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]}
]
}
I would use a defaultdict
to group the labels and values, and then use that dict to create your final structure.
from collections import defaultdict
converted_nested_list = [
{"cmd_count": 2, "name": "jacky", "powered": 10},
{"cmd_count": 9, "name": "madi", "powered": 26},
{"cmd_count": 7, "name": "alisson", "powered": 77},
]
label_stats = defaultdict(list)
for value in converted_nested_list:
for label, stat in value.items():
label_stats[label].append(stat)
result = {
"person_names": label_stats["name"],
"person_details":[
{"label": label, "stats": stats}
for label, stats in label_stats.items()
if label != "name"
]
}
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]}
]
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.