jpedder jpedder - 1 month ago 13x
Python Question

DictReader change keys to upper

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.


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