简体   繁体   English

不返回 python 中的所有项目

[英]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.我正在尝试将我的字典传递给一个新的 function。目前返回值是在调用时打印一行数据。

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 output 是

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.这里的目标是避免 pandas。

CSV is formatted as so CSV 格式如下

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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