Skip to content
Advertisement

Comparing nested dictionaries into general dictionary

I would like to compare multiple nested dictionaries inside a larger dictionary. Suppose we have the following dictionary:

pricesDict = { "supermarket_1": {"apples": 1, "bananas": 2, "melons": 3},
               "supermarket_2": {"apples": 1.5, "bananas": 2, "melons": 3},
               "supermarket_3": {"apples": 1, "bananas": 2, "melons": 3},
               "supermarket_4": {"apples": 1, "bananas": 2.7, "melons": 3}}

I have a pricesDict that contains the prices of some products (more than 3 as shown above) in different supermarkets (more than 4 as shown above).

I want to go through it to compare the nested supermarkets with one another (e.g supermarket_1 with supermarket_2, supermarket_3 and supermarket_4, supermarket_2 with supermarket_3 and supermarket_4 and so on) to find out which one has the lowest prices.

If the programme spots a difference between the price of a specific product in two supermarkets it should print a message to inform us that there is a difference on the prices.

The output should be something like the following:

There is a price difference between supermarket_1: 1 and supermarket_2: 1.5 in apples
There is a price difference between supermarket_1: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_2: 1.5 and supermarket_3: 1 in apples
There is a price difference between supermarket_2: 1.5 and supermarket_4: 1 in apples
There is a price difference between supermarket_2: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_3: 2 and supermarket_4: 2.7 in bananas

Thanks!

Advertisement

Answer

You can do it with itertools.combinations and a nested loop:

from itertools import combinations

for first_market, second_market in combinations(pricesDict, 2):
    for produce in ["apples", "bananas", "melons"]:
        first_price = pricesDict[first_market][produce]
        second_price = pricesDict[second_market][produce]
        
        if first_price != second_price:
            print(
                  f"There is a price difference between {first_market}: {first_price} " +
                  f"and {second_market}: {second_price} in {produce}"
                 )

this prints:

There is a price difference between supermarket_1: 1 and supermarket_2: 1.5 in apples
There is a price difference between supermarket_1: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_2: 1.5 and supermarket_3: 1 in apples
There is a price difference between supermarket_2: 1.5 and supermarket_4: 1 in apples
There is a price difference between supermarket_2: 2 and supermarket_4: 2.7 in bananas
There is a price difference between supermarket_3: 2 and supermarket_4: 2.7 in bananas
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement