Skip to content Skip to sidebar Skip to footer

Find Duplicates Of Dictionary In A List And Combine Them In Python

I have this list of dictionaries: 'ingredients': [ { 'unit_of_measurement': {'name': 'Pound (Lb)', 'id': 13}, 'quantity': '1/2',

Solution 1:

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.


Post a Comment for "Find Duplicates Of Dictionary In A List And Combine Them In Python"