我正在尝试更新一些代码。目前正在学习Python3,想知道是否可以用字典或元组更好地完成此工作?该代码查看一个csv文件并打印出值。我正在尝试更新代码,使其更简单,更可靠(如果可能)。
将样本数据用作:
品牌,型号,年份,颜色,引擎大小,最高速度,传输率
宝马,X6,2018,黑色,4L,240,手动
# use a sample piece of data as:
# brand,model,year,colour,engine_size,top_speed,transmission
# bmw,X6,2018,black,4L,240,manual
import csv
brand, model, year, colour, engine_size, top_speed, transmission = {},
{}, {}, {}, {}, {}, {}
counter = 0
with open("csv_test.csv", 'r') as csvFile:
reader = csv.DictReader(csvFile)
for row in reader:
brand[counter] = row['brand']
model[counter] = row['model']
year[counter] = row['year']
colour[counter] = row['colour']
engine_size[counter] = row['engine_size']
top_speed[counter] = row['top_speed']
transmission[counter] = row['transmission']
counter += 1
csvFile.close()
我知道DictReader将使用第一行作为列名,我想遍历每行并将值打印到屏幕上。
答案 0 :(得分:2)
您不需要在每一列中使用一个字典:您只需在解析中使用list / dict
中的row
(每个 row 是一个字典)。这段代码将行存储在以“行号”为键的字典中(它从不使用此号码做任何事情-因此您可以简单地使用列表)。
创建演示数据:
# use a sample piece of data as:
with open("csv_test.csv","w") as f:
f.write("""brand,model,year,colour,engine_size,top_speed,transmission
bmw,X6,2018,black,4L,240,manual
bmw,X7,2019,green,4L,240,manual
bmw,X8,2020,yellow,4L,240,manual
""")
加载/打印数据:
import csv
data = {}
with open("csv_test.csv", 'r') as csvFile:
reader = csv.DictReader(csvFile)
for num,row in enumerate(reader): # num gives you the row number if you really need it
data[num] = row # put the line of your file into dict, row number is key
print(data)
# print data "nicely"
for d in data:
# get the maximum lenght for your keys to allow a nice formatting
max_key = max(len(i) for k in data for i in data[k])
for k in data[d]:
# format the key to max length so data is aligned
print(f"{k:{max_key}}\t{data[d][k]}")
print()
输出:
# your parsed dict of row-dicts
{0: OrderedDict([('brand', 'bmw'), ('model', 'X6'), ('year', '2018'), ('colour', 'black'),
('engine_size', '4L'), ('top_speed', '240'), ('transmission', 'manual')]),
1: OrderedDict([('brand', 'bmw'), ('model', 'X7'), ('year', '2019'), ('colour', 'green'),
('engine_size', '4L'), ('top_speed', '240'), ('transmission', 'manual')]),
2: OrderedDict([('brand', 'bmw'), ('model', 'X8'), ('year', '2020'), ('colour', 'yellow'),
('engine_size', '4L'), ('top_speed', '240'), ('transmission', 'manual')])}
# the formatted output
brand bmw
model X6
year 2018
colour black
engine_size 4L
top_speed 240
transmission manual
brand bmw
model X7
year 2019
colour green
engine_size 4L
top_speed 240
transmission manual
brand bmw
model X8
year 2020
colour yellow
engine_size 4L
top_speed 240
transmission manual
如果只想按行显示数据,请使用:
# print data in lines
for d in data:
print(*data[d].values(), sep="\t")
输出:
bmw X6 2018 black 4L 240 manual
bmw X7 2019 green 4L 240 manual
bmw X8 2020 yellow 4L 240 manual
相关: