Reputation: 33
I'm trying to resolve import issues in dictreader when fields aren't formatted as expected, forcing all fieldnames to uppercase (or lowercase) would resolve that.
Here's the basic code I'm using, though I can't seem to update the rows in dict.
f = open(sourceFile,'rb')
reader = csv.DictReader(f, dialect='excel')
for r in reader:
r.update(dict((k.upper(), v) for k, v in r.iteritems()))
The desired output is the same list of dictionaries but will all keys set to uppercase.
I'm missing the 'update', I'm fine writing to a new list. Just getting a little frustrated.
Upvotes: 1
Views: 1998
Reputation: 678
To avoid iterating through your entire file, modify the fieldnames
attribute on the DictReader, as in:
f = open(sourceFile,'rb')
reader = csv.DictReader(f, dialect='excel')
reader.fieldnames = [name.upper() for name in reader.fieldnames]
Upvotes: 7
Reputation: 1122542
You could use a generator to return an uppercased keys dictionary for each row:
def uppercased(reader):
for r in reader:
yield {k.upper(): v for k, v in r.iteritems()}
then use this as:
with open(sourceFile,'rb') as f:
reader = csv.DictReader(f, dialect='excel')
for r in uppercased(reader):
# use `r` like you normally would
Upvotes: 2
Reputation: 65791
If you want a new list:
new = [{k.upper(): v for k, v in r.iteritems()} for r in reader]
Or if you want to make one dict at a time:
for r in reader:
r = {{k.upper(): v for k, v in r.iteritems()}
# use r
Upvotes: 1