問題描述
我正在開發一個程序,該程序(除其他外)讀取 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()}
這篇關于如何重新映射 python dict 鍵的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!