简体   繁体   中英

Using csv.DictReader with a slice

I was wondering whether there was a way read all columns in a row except the first one as ints using csv.DictReader, kind of like this:

filename = sys.argv[1]
database = []
with open(filename) as file:
    reader = csv.DictReader(file)
    for row in reader:
        row[1:] = int(row[1:])
        database.append(row)

I know this isn't a correct way to do this as it gives out the error of being unable to hash slices. I have a way to circumvent having to do this at all, but for future reference, I'm curious whether, using slices or not, I can selectively interact with columns in a row without hardcoding each one?

Use this:

import csv

filename = 'test.csv'
database = []
with open(filename) as file:
    reader = csv.DictReader(file)
    for row in reader:
        new_d = {}                                     # Create new dictionary to be appended into database
        for i, (k, v) in enumerate(row.items()):       # Loop through items of the row (i = index, k = key, v = value)
                new_d[k] = int(v) if i > 0 else v      # If i > 0, add int(v) to the dictionary, else add v
        database.append(new_d)                         # Append to database
                
print(database)

test.csv:

Letter,Num1,Num2
A,123,456
B,789,012
C,345,678
D,901,234
E,567,890

Output:

[{'Letter': 'A', 'Num1': 123, 'Num2': 456},
 {'Letter': 'B', 'Num1': 789, 'Num2': 12},
 {'Letter': 'C', 'Num1': 345, 'Num2': 678},
 {'Letter': 'D', 'Num1': 901, 'Num2': 234},
 {'Letter': 'E', 'Num1': 567, 'Num2': 890}]

You can do it by using the key() dictionary method to get a list of the keys in each dictionary and the slice that for doing the conversion:

import csv
from pprint import pprint
import sys


filename = sys.argv[1]
database = []
with open(filename) as file:
    reader = csv.DictReader(file)
    for row in reader:
        for key in list(row.keys())[1:]:
            row[key] = int(row[key])
        database.append(row)

pprint(database)

Output:

[{'name': 'John', 'number1': 1, 'number2': 2, 'number3': 3, 'number4': 4},
 {'name': 'Alex', 'number1': 4, 'number2': 3, 'number3': 2, 'number4': 1},
 {'name': 'James', 'number1': 1, 'number2': 3, 'number3': 2, 'number4': 4}]

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