import csv #Informs Python that we want to use the csv module.
vehicleInventory = {}
with open('cars.csv', newline='') as csvfile:
filereader = csv.DictReader(csvfile, delimiter = ',', quotechar = '"')
counter = 0
for row in filereader:
counter += 1
# TASK 1, copying rows in filereader into a dictionary
vehicleInventory[counter] = row
vehicleInventory[100] = {"model_year": str(2001), "type":"Car", "make":"MINI", "model":"S", "transmission":"6-speed", "primary_color":"Red" }
vehicleInventory[101] = {"model_year": str(2020), "type":"Motorcycle", "make":"Yamaha", "model":"R6", "transmission":"6-speed", "primary_color":"black"}
vehicleInventory[102] = {"model_year": str(2020), "type":"SUV", "make":"Chevrolet", "model":"Suburban", "transmission":"Automatic", "primary_color":"Grey"}
#for key in vehicleInventory:
#print("Vehicle " + str(key) + " information:")
#print("MAKE " + vehicleInventory[key]["make"])
#print("Year: " + vehicleInventory[key]["model_year"])
#print("MODEL " + vehicleInventory[key]["model"])
#print( "Color " + vehicleInventory[key]["primary_color"])
字符串
这是用于查找值的大部分代码,我需要找到模型年份的平均值:
from functools import reduce
def accumulate(x, y):
return x + y
def dict_mean(d):
values_sum = reduce(accumulate, d.values())
mean = values_sum / len(d)
return mean
for key in vehicleInventory:
d = int(vehicleInventory[key]["model_year"])
print (str("Mean:", dict_mean(d)))
型
我尝试了多种方法,这是最新的,但它总是卡住值总和不是一个int的原因,当它通常不应该关心。如果有一个更好的方法,请分享,因为我不知道如果这是远程工作。
1条答案
按热度按时间esbemjvw1#
vehicleInventory
应该是一个字典列表(所以使用方括号)。你应该读取csv文件的每一行,并将其分配给相应的字典,然后将其附加到vehicleInventory
列表中。字符串