Question about the exercise

python

#1

Hello Python community,
I have a problem solving the the following question.
Below is a txt. file randomly made up.

here’s what in the txt. file:

htc,2018/01,100,200,300
htc,2018/02,100,200,300
apple,2018/05,600,600,400
apple,2018/01,600,600,400
dic={}

def parseline(line):   
    line=line.strip()
    arr=line.split(",")
    companyname=arr[0]
    companyearn=arr[2:]
    total=0
    for x in companyearn:
        "print(int(x))"
        total+=int(x)
    dic[companyname]=total


data=open("companyincome1.txt", "r")
for line in data:
    parseline(line)
print(dic)


s="mycompany,2018/02,800,200,300,700,100"
parseline(s)
print(dic)        
    
data.close()

My output is:
{‘htc’: 600, ‘apple’: 1600}
{‘htc’: 600, ‘apple’: 1600, ‘mycompany’: 2100}

Question

  1. how can I let python show the total for the same company even I put the company on a different line. ( Line 1 and Line 2 are both HTC, but it’s not in the same line because it’s a different month)

  2. What function can I use so I can call out a data about the revenue from each company based on the month.
    For example, I type 2018/02, and it will show {htc:600, apple:1600}

Thanks a million for replying


#2

you would need to check if company already is inside your dic dictionary. If so, increase the value belonging to key, else insert new key value pair

not sure, given apple doesn’t have any income for 2018/02, where do you get 1600 from?


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.