0

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!

Gergan Zhekov
  • 944
  • 1
  • 8
  • 27
  • 2
    Yes there is a way but what did you try and what went wrong? It's far more beneficial if we can address your specific misunderstanding than just give you an answer – roganjosh Jun 08 '19 at 11:05

2 Answers2

2

You could define a default dictionary using int

d = collections.defaultdict(int)

and then simply add the values:

d["1 and 2"] += …

where is the value that you keep appending to the lists. The above works because the default value for int is 0; like the default value for a list is the empty list.

Jens
  • 8,423
  • 9
  • 58
  • 78
  • You should note that this actually replaces their initial approach resulting in lists of values, rather than getting the desired output from their existing dict – roganjosh Jun 08 '19 at 11:12
  • @roganjosh, I agree, and I assumed that ultimately the op is interested in the result sum value. – Jens Jun 08 '19 at 11:28
  • Sure, I just mean that the answer might be confusing for them to apply, based on my impression of their understanding of the language, if they don't know that it's an alternative approach rather than a fix – roganjosh Jun 08 '19 at 11:29
2

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}
balderman
  • 22,927
  • 7
  • 34
  • 52