Search code examples
pythondictionarymergedefaultdict

Adding values in a default dictionary - Python (or merging)


I am currently working on a code and I am wondering if there is a way to merge the dictionary values and add them:

Example Dictionary:

defaultdict(<class 'list'>, {'1 and 2': [181, 343], '2 and 5': [820], '2 and 6': [1], '1 and 3': [332], '1 and 4': [77], '3 and 4': [395], '3 and 5': [823]})

Note: 1 and 2, for example, stays for Employees ID 1 and 2, and [181,343] stays for days worked on different projects. I want to merge their total days of working together on projects for the eventual output.

So it would result in:

defaultdict(<class 'list'>, {'1 and 2': [524], ... )

Thanks!


Solution

  • Here

    data = {'1 and 2': [181, 343], '2 and 5': [820], '2 and 6': [1], '1 and 3': [332], '1 and 4': [77], '3 and 4': [395], '3 and 5': [823]}
    
    data_with_sum = {k:sum(v) for k,v in data.items()}
    print(data_with_sum)
    

    output

    {'1 and 2': 524, '2 and 5': 820, '2 and 6': 1, '1 and 3': 332, '1 and 4': 77, '3 and 4': 395, '3 and 5': 823}