如何重新映射 python dict 键
问题描述
我正在开发一个程序,该程序(除其他外)读取 CSV 文件(它以 [{col1:data1a,col2:data2a},{col1:data1b 的形式存储为字典数组,col2:data2b}]
).对于每一行,作为其他处理的一部分,我需要将这些键重新映射到用户输入的值,这些值在另一个 dict 中提供,因此它们可以用作 API 调用中的参数.映射数组的格式为:{badname1:goodname1, badname2:goodname2,...}
.
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,...}
.
所以我想从:
{badname1:data1, badname2:data2,...}` to `{goodname1:data1, goodname2:data2,...}
我想使用类似 zip()
的东西(尽管 zip()
会产生 {badname1:badname1,...}
).
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.
如果数据在a
,映射在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())
...
或者在 Python2.7+ 中使用 字典理解:
Or in Python2.7+ with Dict Comprehensions:
for row in rows:
row = {name_map[name]: val for name, val in row.items()}
相关文章