Adding up a value after matching a line using append from a text file using python 3.x
Question: I have a text file which contains lines as followed

    
    
    Data_1 (2): 01 sec
    Data_1 (1): 01 sec
    Data_1 (1): 02 secs
    Data_2 (2): 04 secs
    Data_1 (3, 1, 2): 2 hrs 40 mins 02 secs
    Data_2 (1): 03 secs
    Data_1 (3, 1, 2): 20 secs
    Data_3 (1): 02 secs
    Data_3 (2): 23 secs
    

I want my output to be like:

    
    
    Data_1 (2): 01 sec
    Data_1 (1): 03 secs
    Data_2 (2): 04 secs
    Data_1 (3, 1, 2): 2 hrs 40 mins 22 secs
    

Just adding up the seconds if values in each line till ":" matches with each
other the seconds values should be summed up irrespective of the position they
are located.

Code till now:

    
    
    with open("folder/file_1", "r") as total_timing:
        variable_number = len(variable_name)
        evaluated_variables = []
        timing = 0
        for val, line in zip(range(0,variable_number),total_timing):
            if variable_name[val] in line:
                value = int((line.split(":")[1]).split()[0])
                timing = value + timing
                if variable_name[val] not in evaluated_variables:
                    print("   > " + variable_name[val] + " " + str(timing))
                    evaluated_variables.append(variable_name[val])
    

I have got `variable_name` from another loop where I retrieve the variables.
But this code doesn't provide what I require. Any help would really great...!


Answer: I think the easiest approach is to split each line into a name string and a
time integer. Then you can store the cumulative values in an ordered dict and
output them once they're all added up.

    
    
    from collections import OrderedDict
    d = OrderedDict()
    with open("folder/file_1") as file:
        for line in file:
            name, _, raw_time = line.rpartition(":")
            time = int(raw_time.strip("sec \n"))
            d[name] = d.get(name,0) + time
    
    for name, time in d.items():
        print("{}: {:02} {}".format(name, time, "sec" if time == 1 else "secs"))
    

Result:

    
    
    Data_1 (2): 01 sec
    Data_1 (1): 03 secs
    Data_2 (2): 04 secs
    Data_1 (3, 1, 2): 04 secs
    Data_2 (1): 03 secs
    Data_3 (1): 02 secs
    Data_3 (2): 23 secs
    

