简体   繁体   中英

Importing a csv file as dictionary in python to later calculate areal values

I have the following problem. I have a .csv files (180 entries) which looks like this:

Codes,Area
3443,0
3530,0
3583,0
3589,0
3514,0

I read that .csv-file into python using this command:

input_file = csv.DictReader(open("CPC.csv"))
for row in input_file:
    print row

The dictionary then looks like this:

{'Codes': '3443', 'Area': '0'}
{'Codes': '3530', 'Area': '0'}
{'Codes': '3583', 'Area': '0'}
{'Codes': '3589', 'Area': '0'}
{'Codes': '3514', 'Area': '0'}

That looks pretty and I really like it. My aim is to calculate area values in m^2 for every code. Therefore this dictionary is just temporary to sum up all areas for their specific codes and to later then take that value and re-assign it to a new table. I have however a problem: how do I access my codes? Therefore I just wanted to have actually this type of dictionary:

{'3443', '0'}
{'3530', '0'}
{'3583', '0'}
{'3589', '0'}
{'3514', '0'}

So that I just need to search for my code (like for example 3443 and that I then can add to the 0 which is there my 125m^2 which are in my other table. I fail to see how to do it. Anybody could help please?

Your original code reads the csv file, parses the format to split the columns, then prints each parsed row. It doesn't store the objects in memory.

You have to choose if you want to store them all in memory, or you want to process them as you go and store the results somewhere else, like, in another file.

From your problem description it seems you will deal with each code separately. However you didn't provide your "other table" so I don't know exactly how it is structured.

The example code below will read the file, code by code, and for each code it will search YOUR_OTHER_TABLE for the value to put in the Area field. Then it will write each row to a separate result file.

Also, it seems you're using python 2, so the example below is also using python 2 specifics (for example, opening csv files in binary mode, in python 3 you don't want that):

with open("CPC.csv", 'rb') as f, open('CPC_result.csv', 'wb') as fw:
    csv_f = csv.DictReader(f)
    csv_w = csv.DictWriter(fw, csv_f.fieldnames)
    for row in csv_f:
        code = row['Codes']
        calculated_area = YOUR_OTHER_TABLE.get(code, 0)
        row['Area'] = str(calculated_area)
        csv_w.writerow(row)
areas = {}
input_file = csv.reader(open("CPC.csv"))
next(input_file)
for row in input_file:
    key, val = row
    areas[key] = val

print areas
#{'3443': '0', '3530': '0', '3583': '0', '3589': '0', '3514': '0'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM