Home > Software engineering >  How to compare values in the same python dictionary and do stuff if match
How to compare values in the same python dictionary and do stuff if match

Time:05-08

I have a dictionary such as :

{
     "number_1":
    {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "number_2":
    {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "number_3":
    {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
    "number_4":
    {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
}

I need a generic way to get the total of values if dictionaries has the same value for the key month_year so for example for month_year 5/2022 it's gonna be :

{
    "month_year": "5/2022",
    "total_price": 2,
    "total_average": 2,
    "total_covered": 2,
}

CodePudding user response:

Like other answers you may have already seen, your dictionary is not formatted correctly. Because your sub-dictionaries are inside a dictionary, you must give them a key as well. Here is an example:

{
    "1st Dictionary": {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "2nd Dictionary": {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "3rd Dictionary": {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
    "4th Dictionary": {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
}

Here you are giving each sub-dictionary a key. Each key simply states which dictionary in the dictionary of dictionaries it is. Here is an alternative method:

{
    0: {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    1: {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    2: {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
    3: {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
}

This is the same thing except you are using numbers 0-3. This may be a better idea because this way you are giving a key similar to an index.

Now back to your question! If you wanted to get a certain index of either of these dictionaries, you would first have to define a variable with said dictionary, and then type the key inside brackets next to the variable (similar to a list). For simplicity, I will use the first dictionary. Here is what I’m talking about:

dictionary={
    "1st Dictionary": {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "2nd Dictionary": {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    "3rd Dictionary": {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
    "4th Dictionary": {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
}

if dictionary["1st Dictionary"]["price"]>1:
    print("if statement ran successfully!")

elif dictionary["1st Dictionary"]["price"]==1:
    print("elif statement ran successfully!")

Here, the output is: elif statement ran successfully!

What we are doing here is getting the key named “1st Dictionary” and then the key named “price” inside of said dictionary. Here is an example of this behavior with lists:

my_list=[
    [1,2,3],
    ["a","b","c"],
    [0.1,0.2,0.3]
]

if my_list[0][1]==2:
    print("if statement ran successfully!")

If we run this code, we get the output: if statement ran successfully!

Here we are checking if the second index inside of the first list inside of my_list is equal to 2. Just for clarification, here you can see that the first index of my_list is [1,2,3], and that the second index of the first index of my_list is 2.

my_list[0]==[1,2,3]

my_list[0][1]==2

Hopefully this answered your question in a simple and easy-to-understand way!

CodePudding user response:

You can try the below solution

#Assuming you have list of dictionaries bcz set of dictionaries is not possible due to unhashable type dicts

a = [
    {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    {
        "month_year": "5/2022",
        "price": 1,
        "average": 1,
        "covered": 1,
    },
    {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
    {
        "month_year": "4/2022",
        "price": 10,
        "average": 93,
        "covered": 100,
    },
]
from itertools import groupby
from collections import Counter

print(
    [
        {
            **sum(
                (
                    Counter(vals)
                    for vals in val
                    if (_ := vals.pop("month_year"))
                ),
                Counter(),
            ),
            **{"month_year": key},
        }
        for key, val in groupby(a, key=lambda x: x["month_year"])
    ]
)

Explanation: First groupby with keys month_year we get unique key of month_year and list of values of that group where we applied (sum of two dictionaries using Counter) and then put back my key in the resultant dictionary.

  • Related