【问题标题】:Add values for dictionary with same key and value pair为具有相同键值对的字典添加值
【发布时间】:2019-11-02 12:07:02
【问题描述】:

我想合并基于相同键值对的字典列表。我有一个字典列表作为

[{'id':1, 'total':100,'free_from':250},{'id':2,....},{'id':1,......}]

我想从中创建一个具有相同结构的新字典列表,但如果两个字典的 id 相同,则应添加它们的总数,而不是将字典添加到新列表中。

这是字典列表

products = [{'id':1,'total':20,'free_from':250,},{'id':2,'total':30,'free_from':150},{'id':1,'total':10,'free_from':250,},{'id':1,'total':10,'free_from':250},{'id':2,'total':40,'free_from':150, }]

预期结果是

[{ 'id': 1,'total': 40, 'free_from': 250}, {'id': 2,'total': 70, 'free_from': 150}]

我通过使用以下方法设法实现了这一点。但是,如果有人可以帮助我找到更好的方法来做到这一点,那将是很大的帮助。

category_delivery_list=[]
products = [
    {
        'id':1,
        'total':20,
        'free_from':250,
    },{
        'id':2,
        'total':30,
        'free_from':150, 
    },{
        'id':1,
        'total':10,
        'free_from':250, 
    },{
        'id':1,
        'total':10,
        'free_from':250, 
    },{
        'id':2,
        'total':40,
        'free_from':150, 
    }
]
for data in products:
    if category_delivery_list:
        index = None
        for count, cat in enumerate(category_delivery_list):
            if cat['id'] == data['id']:
                index=count
        if index >= 0:
            category_delivery_list[index]['total'] += data['total']
            category_delivery_list[index]['free_from'] = data['free_from']
        else:
            category_delivery_list.append({
                'id':data['id'],
                'total':data['total'],
                'free_from':data['free_from']
            })
    else:
        category_delivery_list.append({
            'id':data['id'],
            'total':data['total'],
            'free_from':data['free_from']
        })
print(category_delivery_list)

【问题讨论】:

    标签: python-3.x dictionary


    【解决方案1】:

    这样做的一个好方法是通过临时字典:

    temp = {}
    for data in products:
        if data["id"] in temp:
            temp[data["id"]]["total"] += data["total"]
            temp[data["id"]]["free_from"] += data["free_from"]
        else:
            temp[data["id"]] = data.copy()
    category_delivery_list = list(temp.values)
    

    这将创建一个临时字典 id -> {'id':.., 'total':..., 'free_from':...},然后遍历列表并添加新条目或添加到现有条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      相关资源
      最近更新 更多