0

If my input has a list of products and it's quantities separated by spaces, I would like to make a python code which will output unique values of products and the sum of quantities for each product.

Input:

Product1 3
Product2 3
Product3 6
Product2 5
Product1 1
Product1 2
Product321 4
Product4 2
Product5 3
Product3 4
Product1 1
Product2 2
Product5 4
Product321 5

Output:

Product1 7
Product2 10
Product3 10
Product4 2
Product5 7
Product321 9
  • 2
    That's not actually a question. Moreover, each component of the problem (how to read in lines from a file, how to group and combine values) has already been asked and answered on SO many times. – DSM Feb 02 '16 at 03:18

2 Answers2

1

how to open/read files: How to Open a file through python

how to sum up recurrence in stuff: item frequency count in python

how to split up a string in python: How to split a string into a list?


Putting them together I came up with this:

from collections import defaultdict

info = defaultdict(int)

with open("PATH_TO_INPUT","r") as f_in:
    for line in f_in:
        name,number = line.split(" ")
        info[name]+=int(number)

with open("PATH_TO_OUTPUT","w") as f_out:
    f_out.write("\n".join("%s %s"%pair for pair in info.items()))

It is not as verbose as it could be but every single aspect of this task is very well described elsewhere.

Community
  • 1
  • 1
Tadhg McDonald-Jensen
  • 17,001
  • 3
  • 29
  • 51
  • Thank you very much, I'm new here and I didn't realize I had to supply the code I had done. –  Feb 02 '16 at 04:38
0

Welcome to stackoverflow. Just so you know, this is where you request others correct your code, not write code for you. You need to try something first and if there is a problem with your implementation, you can ask how to fix it if you cannot fix it after trying for some time.

Here, let me give you some hints to solve the problem:

  1. Install Pandas (http://pandas.pydata.org/) .
  2. Learn about the commands

    2.1. read.csv

    2.2. group_by

    2.3. agg

    2.4. reset_index

Using these, you should be able to complete the problem in a single line of text. Please try.

ssm
  • 4,867
  • 1
  • 18
  • 33
  • Thank you very much, I'm new here and I didn't realise I had to supply the code I had done. I will look into pandas. :) –  Feb 02 '16 at 04:37