How do I re-map python dict keys

Python 3.7

d = {'badname1': 'data1', 'badname2': 'data2'}
m = {'badname1': 'goodname1', 'badname2': 'goodname2'}

{ m[k]:d[k] for k in d }

Outputs

{'goodname1': 'data1', 'goodname2': 'data2'}

rows = [{"col1":"data1a","col2":"data2a"},{"col1":"data1b","col2":"data2b"}]
name_map = {"col1":"newcol1","col2":"newcol2"}

new_rows = [dict(zip(map(lambda x: name_map[x], r.keys()), r.values())) for r in rows]

Is this what you are after?


If you are using Python 2.7 or Python 3.x, you can use a dictionary comprehension. This is equivalent elo80ka's answer (which used a list comprehension), but produces slightly more readable code.

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

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

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