如何重新映射 python dict 键

How do I re-map python dict keys(如何重新映射 python dict 键)
本文介绍了如何重新映射 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()}

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)