Search code examples
pythonloopsdictionarynestedlist-comprehension

How can i sum the elements of the list in the nested dictionary


I have an dictionary as below

dict= {
('201', '1'): {'357': [1, 67500], '360': [1, 40000], '362': [2, 45000], '365': [1, 12500]},
('301', '2'): {'322': [5, 237500]},
('301', '1'): {'325': [10, 675000]}
}

I want to get the result as below :

'''165000 is the sum of the second elements of the lists e.g. [1, 67500]'''

{
('201', '1'): 165000},
('301', '2'): 237500},
('301', '1'): 675000}
}

Can you show your codes--- any solutions would be helpful - comprehension, Counter and so on

{('201', '1'): 165000},('301', '2'): 237500},('301', '1'): 675000}}

Solution

  • Try:

    dct = {
        ("201", "1"): {
            "357": [1, 67500],
            "360": [1, 40000],
            "362": [2, 45000],
            "365": [1, 12500],
        },
        ("301", "2"): {"322": [5, 237500]},
        ("301", "1"): {"325": [10, 675000]},
    }
    
    out = {}
    for k, v in dct.items():
        out[k] = sum(vv for _, vv in v.values())
    
    print(out)
    

    Prints:

    {("201", "1"): 165000, ("301", "2"): 237500, ("301", "1"): 675000}
    

    Or:

    out = {k: sum(vv for _, vv in v.values()) for k, v in dct.items()}