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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With