data = [{'_id': '500104 ',' count': 3},
{'_id': '440604 ',' count': 1},
{'_id': '410304 ',' count': 2},
{'_id': '410305 ',' count': 9},
{'_id': '500107 ',' count': 8},
{'_id': '440605 ',' count': 9}]
結果= {}
對於數據中的項目:
key = item['_id'][:4]
如果鍵不在結果中:
結果[關鍵字] =項目['計數']
否則:
結果[關鍵字] +=項目['計數']
output = [{'_id': key,' count': value} for key,value in result.items()]
打印(輸出)
輸出結果是:
[{'_id': '5001 ',' count': 11},{'_id': '4406 ',' count': 10},{'_id': '4103 ',' count': 11}]