如何重新映射python dict键 [英] How do I re-map python dict keys

查看:162
本文介绍了如何重新映射python dict键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个程序(其中包括)读取一个CSV文件(它被存储为一组数组,格式为 [{col1:data1a,col2:data2a},{ col1:data1b,col2:data2b}] )。对于每行,作为其他处理的一部分,我需要将这些键重新映射到用户输入的值,这些值在另一个dict中提供,以便它们可以用作API调用中的参数。映射数组的格式为: {badname1:goodname1,badname2:goodname2,...}



所以我想从:
{badname1:data1,badname2:data2,...} {goodname1:data1 ,goodname2:data2,...}



我想使用类似 zip()(虽然 zip()产生 {badname1:badname1,...} )。 p>

似乎应该有一个明显的解决方案暗示我。



编辑:
如果数据在 a b 中的映射:



dict(zip(b,a.itervalues()))



我接近,但只会工作在这种情况下,我们认为这些字段的顺序是相同的。

解决方案

  name_map = {'oldcol1':'newcol1','oldcol2':'newcol2','oldcol3':'newcol3'...} 

行中的行:
#每行是形容词:{'o ldcol1':'...','oldcol2':'...'}
row = dict((name_map [name],val)for name,val in row.iteritems())
...

或在Python2.7 +与 Dict Comprehensions

 对于行行:
row = {name_map [name]:val for name,val in row.items()}


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.

解决方案

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()}

这篇关于如何重新映射python dict键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆