Computing a population by creating a nested dictionary on the go

I am new to python and at the moment I can really use your help and recommendations. I am trying to read a csv file with three columns and do some calculations based on the first and second columns i.e.

A   spent   100     A   spent   2040
A   earned  60
B   earned  48
B   earned  180
A   spent   40
.
.
.

If spent 2040 will be the addition of all amounts "A" and "spent". This does not give me an error, but it is not logically correct:

for row in rows:
    cols = row.split(",")
    truck = cols[0]
    if (truck != 'A' and truck != 'B'):
        continue
    record = cols[1]
    if(record != "earned" and record != "spent"):
        continue
    amount = int(cols[2])
    #print(truck+" "+record+" "+str(amount))

    if truck in entries:
        #entriesA[truck].update(record)
        if record in records:
            records[record].append(amount)
        else:
            records[record] = [amount]
    else:
        entries[truck] = records
        if record in records:
            records[record].append(amount)
        else:
            entries[truck][record] = [amount]
print(entries)

I know this part is incorrect because I would add the same internal list of dictionaries to an external dictionary, but I'm not sure how to go from there:

entries[truck] = records
if record in records:
    records[record].append(amount)

However, I am not sure of the syntax for creating a new dictionary "on the fly", which would not be "records"

I get:

{'B': {'earned': [60, 48], 'spent': [100]}, 'A': {'earned': [60, 48], 'spent': [100]}}

But hope to get:

{'B': {'earned': [48]}, 'A': {'earned': [60], 'spent': [100]}}

Thank.

+4
2

, , Pandas.

, in.csv :

truck,type,amount
A,spent,100
A,earned,60
B,earned,48
B,earned,180
A,spent,40

:

import pandas
df = pandas.read_csv('in.csv')
totals = df.groupby(['truck', 'type']).sum()

totals :

              amount
truck type          
A     earned      60
      spent      140
B     earned     228

, Pandas .

+2
if record in entries[truck]:
    entries[truck][record].append(amount)
else:
    entries[truck][record] = [amount]

, , ? , , records. , , .

0

Source: https://habr.com/ru/post/1656292/


All Articles