views:

630

answers:

2

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.

EDIT: 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.

+3  A: 
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()])
    ...
elo80ka
Yep. Also works without the [], as a generator expression.
dF
+1  A: 
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?

Jon