Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 992
acrosman Avatar asked Mar 13 '09 19:03

acrosman


People also ask

How do you update dictionary keys?

Since keys are what dictionaries use to lookup values, you can't really change them. The closest thing you can do is to save the value associated with the old key, delete it, then add a new entry with the replacement key and the saved value.

How do I map multiple keys to the same value in Python?

In Python dictionary, if you want to display multiple keys with the same value then you have to use the concept of for loop and list comprehension method. Here we create a list and assign them a value 2 which means the keys will display the same name two times.


2 Answers

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()} 
like image 97
elo80ka Avatar answered Oct 14 '22 00:10

elo80ka


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?

like image 43
Jon Avatar answered Oct 13 '22 23:10

Jon