【Python】 list dict数据合并汇总demo
【Python】 list dict数据合并汇总demo
需求:
-
将列表a,根据company进行分类,同一个company的id放到一个列表里面
数据:
a = [{
"id": 214,
"company": "CN920A"
},
{
"id": 225,
"company": "CN920A"
},
{
"id": 239,
"company": "CN920A"
},
{
"id": 226,
"company": "CN920E"
},
{
"id": 236,
"company": "CN920E"
},
{
"id": 194,
"company": "CN920E"
},
{
"id": 193,
"company": "CN930D"
},
{
"id": 192,
"company": "CN930D"
},
{
"id": 191,
"company": "CN940F"
},
{
"id": 190,
"company": "CN940F"
}
]
代码:
def data_merge(a):
classified_case_sensitive = {}
for item in a:
company = item['company']
item_id = item['id']
if company not in classified_case_sensitive:
classified_case_sensitive[company] = []
classified_case_sensitive[company].append(item_id)
print(classified_case_sensitive)
if __name__ == '__main__':
data_merge(a)
结果:
{‘CN920A’: [214, 225, 239], ‘CN920E’: [226, 236, 194], ‘CN930D’: [193, 192], ‘CN940F’: [191, 190]}