0

I'm trying to update some code. Am learning Python3 at the moment and wondering if this could be done better with a dictionary or tuple perhaps? The code looks at a csv file & prints the values out. I'm trying to update the code to make it simpler and more robust (if possible).

use a sample piece of data as:

brand,model,year,colour,engine_size,top_speed,transmission
bmw,X6,2018,black,4L,240,manual

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

I know DictReader will use the top row as column name, I want to go through each row & print the values to the screen.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
T0MM91
  • 19
  • 4
  • why would you want so many dictionarys - if you just need the rows? for simply printing the values a `print(*row)` would be enough ... – Patrick Artner Jun 20 '19 at 09:09
  • Hey Patrick, I'm asking whether this is the best or simplest way to do this or if there's an easier way? When printed, I want to to show say bmw X6 2018 black 4L 240 manual – T0MM91 Jun 20 '19 at 09:16
  • This is probably not the best way because you are not printing anything. But hopefully you know how to print? – Stop harming Monica Jun 20 '19 at 09:58

1 Answers1

2

You do not need one dictionary per column: you only need a list / dict of row (each row is a dict) from your parsing. This code stores the lines in a dict with the "line-number" as key (it never uses this number for anything - so you might simply use a list instead).

Create demodata:

# 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
""")

Load/print data:

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

Output:

# 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

If you just want the data in lines, use:

# print data in lines
for d in data:
    print(*data[d].values(), sep="\t")

Output:

bmw X6  2018    black   4L  240 manual
bmw X7  2019    green   4L  240 manual
bmw X8  2020    yellow  4L  240 manual

Related:

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69