如何在新词典中添加对? [字典],然后将相同键的值求和

时间:2019-11-21 19:59:05

标签: python dictionary

我需要在代码的这一部分中添加一些对。例如afmLine[1]= 0000000001(这是公司的ID)和成本。然后,当在字典中有多次相同的afmLine号时,我要对该afmLine号的成本求和。用户输入是一个txt文件,例如在我的文件中companyID是“ΑΦΜ”的位置。公司收据是我制作的每张收据的列表。


公司ID:000000000000 披萨:2 3.15 6.30 意大利面:1 7 7

ribye:2 40 80

公司ID:000000000001 汉堡:1 3.15 6.30 意大利面:1 7 7

ribye:2 40 80

product=input('\nGive me the product name: ')
for receipt in company_receipts:
    for line in receipt.split('\n'):
        if product in line:
            seperateLine=line.split('\t')
            Cost=float(seperateLine[3])
            for line in receipt.split('\n'):
                if line.startswith("ΑΦΜ"):
                    afmLine=line.split(' ')
                    afm=afmLine[1]
                    diction=????

2 个答案:

答案 0 :(得分:0)

您的问题不是很清楚。但是,我认为这就是您想要的:

product=input('\nGive me the product name: ')
diction = {} # Initialize Dict
for receipt in company_receipts:
    for line in receipt.split('\n'):
        if product in line:
            seperateLine=line.split('\t')
            Cost=float(seperateLine[3])
            for line in receipt.split('\n'):
                if line.startswith("ΑΦΜ"):
                    afmLine=line.split(' ')
                    afm=afmLine[1]
                    if afm not in diction: # Check the item in the dictionary
                        diction[afm] = [] # Initialize the value with an empty list
                    diction[afm].append(cost) # Append the cost to the dictionary

# Calculating the total cost and printing it per item (i.e. id)
for item in diction:
    totalCost = 0
    for cost in diction[item]:
        totalCost += cost
    print(totalCost)

您需要初始化字典,然后在其中添加项目。最后,您可以再次遍历字典并计算每个id的总费用。

答案 1 :(得分:0)

非常感谢您的回复。这对我帮助很大。 我已经有这样的字典 diction = {'AΦΜ':afm,'cost':cost}。 我想要每个AFM的总成本而不是总成本!也许我的词典中有很多次相同的键具有不同的成本。并将afm保留在我的词典中一次