Combining output values ​​into a file

I have a file that has 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 need to generate the output, which will look like this:

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

i.e. if a is valuepresent twice, then during the recording of the output we write valueonly once and summarize countthis value.
I thought this could be done using a function defaultdict, but I'm confused about how to sum the value.
please, help.

+3
source share
3 answers

if you do not care about the order of the elements, then you can use the Karls method.

otherwise use a sorted dict:

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

defaultdict, , , :

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

.

+4

collections.Counter. -

counter = collections.Counter()
for a, b in data: counter.update({a: b})
+2

ordereddict

mydict = ordereddict()

try:
    mydict[val] = mydict[val] + additional_val
except KeyError:
    mydict[val] = additional_val
-2
source

All Articles