Find duplicates of dictionary in a list and combine them in Python

后端 未结 1 1372
一个人的身影
一个人的身影 2021-01-25 00:04

I have this list of dictionaries:

"ingredients": [
            {
                "unit_of_measurement": {"name": "Pound (Lb)&qu         


        
相关标签:
1条回答
  • 2021-01-25 00:52

    Assuming you have a dictionary represented like this:

    data = {
        "ingredients": [
            {
                "unit_of_measurement": {"name": "Pound (Lb)", "id": 13},
                "quantity": "1/2",
                "ingredient": {"name": "Balsamic Vinegar", "id": 12},
            },
            {
                "unit_of_measurement": {"name": "Pound (Lb)", "id": 13},
                "quantity": "1/2",
                "ingredient": {"name": "Balsamic Vinegar", "id": 12},
            },
            {
                "unit_of_measurement": {"name": "Tablespoon", "id": 15},
                "ingredient": {"name": "Basil Leaves", "id": 14},
                "quantity": "3",
            },
        ]
    }
    

    What you could do is use a collections.defaultdict of lists to group the ingredients by a (name, id) grouping key:

    from collections import defaultdict
    
    ingredient_groups = defaultdict(list)
    for ingredient in data["ingredients"]:
        key = tuple(ingredient["ingredient"].items())
        ingredient_groups[key].append(ingredient)
    

    Then you could go through the grouped values of this defaultdict, and calculate the sum of the fraction quantities using fractions.Fractions. For unit_of_measurement and ingredient, we could probably just use the first grouped values.

    from fractions import Fraction
    
    result = [
        {
            "unit_of_measurement": value[0]["unit_of_measurement"],
            "quantity": str(sum(Fraction(ingredient["quantity"]) for ingredient in value)),
            "ingredient": value[0]["ingredient"],
        }
        for value in ingredient_groups.values()
    ]
    

    Which will then give you this result:

    [{'ingredient': {'id': 12, 'name': 'Balsamic Vinegar'},
      'quantity': '1',
      'unit_of_measurement': {'id': 13, 'name': 'Pound (Lb)'}},
     {'ingredient': {'id': 14, 'name': 'Basil Leaves'},
      'quantity': '3',
      'unit_of_measurement': {'id': 15, 'name': 'Tablespoon'}}]
    

    You'll probably need to amend the above to account for ingredients with different units or measurements, but this should get you started.

    0 讨论(0)
提交回复
热议问题