简体   繁体   中英

How do I re-map python dict keys

I am working on a program that (among other things) reads a CSV file in (it gets stored as an array of dicts in the form [{col1:data1a,col2:data2a},{col1:data1b,col2:data2b}] ). For each row, as part of other processing, I need to remap those keys to user entered values, which are provided in another dict so they can be used as parameters in an API call. The mapping array is in the form: {badname1:goodname1, badname2:goodname2,...} .

So I'd like to get from:

{badname1:data1, badname2:data2,...}` to `{goodname1:data1, goodname2:data2,...}

I'd like to use something like zip() (although zip() yields {badname1:badname1,...} ).

Seems like there should be an obvious solution that is alluding me.

If the data is in a and the mapping in b :

dict(zip(b,a.itervalues()))

I get close, but it will only work in cases where the fields are known to be in the same order I think.

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

This function will let you remap only the keys you need to change.

def key_remapper(dictionary: dict):
    return {remap_dictionary.get(k, v): v for k, v in dictionary.items()}

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'}

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