Python – Combines the output values in the file

Combines the output values in the file… here is a solution to the problem.

Combines the output values in the file

I have a file with the following values:

123 9   
111 5   
12 1   
123 4   
12 4   
109 5   
12 4    
35 7   
111 4   
124 6  

Now we must produce output like this:

123 13  
111 9  
12 5  
109 5  
35 7  
124 6

That is, if the value appears twice, then we write the value only once during the write output and summarize the count >
of the value
I think it can be done using the defaultdict function, but I’m confused about how to sum the value.
Please help.

Solution

If you don’t care about the order of the elements, then you can use the Karls method.

Otherwise, use a sorted dictionary:

import collections
data = [(123, 9), (111, 5), (12, 1), (123, 4), (12, 4),
        (109, 5), (12, 4), (35, 7), (111, 4), (124, 6)]

order = collections. OrderedDict()
for value, count in data:
    order[value] = order.setdefault(value, 0) + count

It’s similar to using defaultdict, where you can pass a function at construction time that returns the default value for a key not found in the dictionary:

import collections
default = collections.defaultdict(int)
for value, count in data:
    default[value] += count

But in that case, the order of the elements is also not preserved.

Related Problems and Solutions