简体   繁体   中英

dict not returning all items in python

Long story short. Im trying to pass my dictionary to a new function. Currently the return is printing one row of data when called.

import csv

def csvRead():
    with open('data.csv', 'r', newline='') as f:
        rcsv = csv.DictReader(f, delimiter=',')
        mydict = {}

    for line in rcsv:
        for k, v in line.items():
            mydict[k] = float(v)*2
            print(mydict.items())
    return mydict.items()


print('current: ', csvRead())

Im not entirely sure why this is happening.

the output is

dict_items([('Velocity', 2.2)])
dict_items([('Speed', 111.0)])
dict_items([('Acceleration', 44.4)])
dict_items([('Velocity', 6.6)])
dict_items([('Speed', 8.8)])
dict_items([('Acceleration', 13.2)])
Current: dict_items([('Velocity', 6.6), ('Speed', 8.8), ('Acceleration', 13.2)]}

The goal here is to avoid pandas.

CSV is formatted as so

Velocity,Speed,Acceleration
1.1,55.5,22.2
3.3,4.4,5.5
8.8,9.9,5.5

In your loop you are overwriting your dict values. I implemented it now in a way, in which your dict is initialized with empty lists as values and the read data is appended to these lists:


mydict = {key: [] for key in rcsv.fieldnames}
for line in rcsv:
        for k, v in line.items():
            mydict[k].append(float(v)*2) # <-- you were overwriting the value in each loop
            print(mydict.items())

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