How do I re-map python dict keys

name_map = {'oldcol1': 'newcol1', 'oldcol2': 'newcol2', 'oldcol3': 'newcol3'...}

for row in rows:
    # Each row is a dict of the form: {'oldcol1': '...', 'oldcol2': '...'}
    row = dict((name_map[name], val) for name, val in row.iteritems())
    ...

Or in Python2.7+ with Dict Comprehensions:

for row in rows:
    row = {name_map[name]: val for name, val in row.items()}

Leave a Comment