所以我在Python中有一个字典列表如下:
[
{'medication_name': 'Actemra IV',
'timeline': '2015-Jun',
'total_prescriptions': 1
},
{'medication_name': 'Actemra IV',
'timeline': '2015-Jul',
'total_prescriptions': 0
},
{'medication_name': 'Adempas',
'timeline': '2015-Jun',
'total_prescriptions': 0
},
{'medication_name': 'Adempas',
'timeline': '2015-Jul',
'total_prescriptions': 0
},
{'medication_name': 'Adempas',
'timeline': '2015-Aug',
'total_prescriptions': 0
},
{'medication_name': 'Avonex',
'timeline': '2015-Jun',
'total_prescriptions': 1
},
{'medication_name': 'Avonex',
'timeline': '2015-Jul',
'total_prescriptions': 0
}
]
我想要的是整理每个药物名称的月度值,以便最终结果如下:
[
{'medication_name': 'Actemra IV',
'trend':[
{'timeline': '2015-Jun',
'total_prescriptions': 1
},
{'timeline': '2015-Jul',
'total_prescriptions': 0
},
{'timeline': '2015-Jun',
'total_prescriptions': 0
}
]
},
{'medication_name': 'Adempas',
'trend':[
{'timeline': '2015-Jul',
'total_prescriptions': 0
},
{'timeline': '2015-Aug',
'total_prescriptions': 0
}
]
},
{'medication_name': 'Avonex'
'trend':[
{'timeline': '2015-Jun',
'total_prescriptions': 1
},
{'timeline': '2015-Jul',
'total_prescriptions': 0
}
]
}
]
我将如何做到这一点?
答案 0 :(得分:1)
这应该有用(meds
是带有dicts的列表):
tmp = {}
for med in meds:
name = med.pop('medication_name')
tmp.setdefault(name, []).append(med)
res = [{'medication_name': k, 'trend': v} for k, v in tmp.items()]
结果:
>>> res
[{'medication_name': 'Avonex',
'trend': [{'timeline': '2015-Jun', 'total_prescriptions': 1},
{'timeline': '2015-Jul', 'total_prescriptions': 0}]},
{'medication_name': 'Actemra IV',
'trend': [{'timeline': '2015-Jun', 'total_prescriptions': 1},
{'timeline': '2015-Jul', 'total_prescriptions': 0}]},
{'medication_name': 'Adempas',
'trend': [{'timeline': '2015-Jun', 'total_prescriptions': 0},
{'timeline': '2015-Jul', 'total_prescriptions': 0},
{'timeline': '2015-Aug', 'total_prescriptions': 0}]}]
这会修改原始数据。您可以使用copy.deepcopy()
来避免这种情况:
import copy
tmp = {}
for med in copy.deepcopy(meds):
...