user11652533
user11652533

Reputation:

How to compare two lists of dictionaries by the same key?

I have to lists of dictionaries:

basket = [{"size": "big", "food": "cheese"}, {"size": "small", "food": "cherries"}]
fruits = [{"size": "small", "food": "blueberries"}, {"size": "small", "food": "cherries"}]

I need to compare these two lists of dicts by the "food" key. If a fruit is not in the basket list, I want to append the whole dictionary into the basket list.

I was trying to do it with filter(), but I cannot visualize a scenario where I can call basket[food] and iterate through the fruits lists at the same time.

Upvotes: 2

Views: 231

Answers (2)

You can go through the two lists using the zip method, check if there is one of the keys of the fruit list in the basket list, if there is you go through the fruit list and create a conditional to check if this food is already in the list, if not are you add

basket = [{"size": "big", "food": "cheese"}, {"size": "small", "food": "cherries"}]
fruits = [{"size": "small", "food": "blueberries"}, {"size": "small", "food": "cherries"}]

for bask, fruit in zip(basket, fruits):
  if bask['food'] == fruit['food']:
    for fruit in fruits: 
      if bask['food'] != fruit['food']:
        basket.append(fruit)

print(basket)

output:

[{'size': 'big', 'food': 'cheese'}, {'size': 'small', 'food': 'cherries'}, {'size': 'small', 'food': 'blueberries'}]

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195418

You can create temporary set that contains all food already in basket and then extend the basket list by food that isn't in this set:

basket = [
    {"size": "big", "food": "cheese"},
    {"size": "small", "food": "cherries"},
]
fruits = [
    {"size": "small", "food": "blueberries"},
    {"size": "small", "food": "cherries"},
]

in_basket = set(f["food"] for f in basket)

basket.extend(f for f in fruits if f["food"] not in in_basket)
print(basket)

Prints:

[
    {"size": "big", "food": "cheese"},
    {"size": "small", "food": "cherries"},
    {"size": "small", "food": "blueberries"},
]

Upvotes: 2

Related Questions