简体   繁体   中英

how to creat a dictionary with tuple as a value from csv file?

Can anyone tell me on how to create a dictionary from CSV FILE in the following format(a tuple inside a dictionary)…. { 'a' : (2.0,3.0), 'b' : (60.0 , 0.0), 'c': (100.0 , 0.0)} the keys and the values are a ROWS in the csv file.

I tried this way, but all I am getting is a separate dictionaries instead of one dictionary. thanks

import csv
with open('Book1.csv') as csvfile:
    rdr = csv.reader(csvfile)
    for row in rdr:
        d={row[0]:(float(row[1]),float(row[2]))}

    print(d)

You are creating a dictionary in each iteration, do this instead:

import csv

with open('Book1.csv') as csvfile:
    rdr = csv.reader(csvfile)
    d = {row[0]: (float(row[1]), float(row[2])) for row in rdr}
    print(d)

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