首页 > 解决方案 > 用 dicts 制作相同的列表,但只有唯一的记录

问题描述

list = [
    {'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
    {'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
    {'status': u'Purchase', 'phantom': False, 'row_no': 3, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
    {'status': u'Purchase', 'phantom': False, 'row_no': 4, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
    {'status': u'Purchase', 'phantom': False, 'row_no': 5, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0}  
]

我有这个列表,里面有字典,你可以看到有两行带有product_id 25872,树行带有product_id 25875

如何查看列表中的所有 dicts 并使用 dicts 制作相同的列表,但每个产品只有 1 行?并且'qty'应该总结一下。

所以从这个列表中,我想得到像

list = [
    {'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 2.0, 'cost': 14.0},
    {'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25875, 'standard_price': 14.0, 'qty': 3.0, 'cost': 14.0},
]

标签: pythonpython-2.7

解决方案


我认为在python 的理解的itertools.groupby帮助下应该足够了。尝试这个:sumlist

from itertools import groupby

lst = [
        {'status': u'Purchase', 'phantom': False, 'row_no': 1, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
        {'status': u'Purchase', 'phantom': False, 'row_no': 2, 'product_id': 25872, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
        {'status': u'Purchase', 'phantom': False, 'row_no': 3, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
        {'status': u'Purchase', 'phantom': False, 'row_no': 4, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0},
        {'status': u'Purchase', 'phantom': False, 'row_no': 5, 'product_id': 25875, 'standard_price': 14.0, 'qty': 1.0, 'cost': 14.0}  
]

# Sort the list first, by `product_id`
lst = sorted(lst, key=lambda x:x['product_id'])

# This is where we will store our unique rows
agg = []
row_count = 1

for k,v in groupby(lst,key=lambda x:x['product_id']):
        as_list = list(v)
        as_list[0].update({
                'qty': sum([row['qty'] for row in as_list]),
                'row_no': row_count
        })
        agg.append(as_list[0])
        row_count += 1

# Print the final result
print(agg)

注意:请不要list用作变量名。


推荐阅读