将函数应用于 Python 字典的所有键 [英] Apply a function to all keys of a Python dict

查看:42
本文介绍了将函数应用于 Python 字典的所有键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转换 Python dict 的所有键.

比如key是整数,我想把每个key改成原来的值乘以100.

实现这一目标的最高效的方法是什么?

我现在的做法是将原始密钥存储在 set 中并删除这些密钥,用新密钥替换它们 - 如果我有 key=2 和原始键集中的 key=200 会发生冲突,我必须递归处理,直到找到与原始键没有冲突的键-设置.

解决方案

您可以使用 dict 理解:

<预><代码>>>>d = {1:'a',2:'b',3:'c'}>>>{k*100: v for k, v in d.items()}{200:'b',300:'c',100:'a'}

如果您使用的是 Python 2,请将 items() 替换为 iteritems().

I want to transform all the keys of a Python dict.

For example, if the keys are integers, I want to change each key to be the original value multiplied by 100.

What is the most performance-efficient way to achieve this?

The way I am doing it right now is by storing the original keys in a set and deleting those keys, replacing them by new keys - this had a problem that if I had a key=2 and a key=200 in the original key set, there would be collision, which I would have to handle recursively until I find a key with no collision with the original key-set.

解决方案

You can use a dict comprehension:

>>> d = {1: 'a', 2: 'b', 3: 'c'}
>>> {k*100: v for k, v in d.items()}
{200: 'b', 300: 'c', 100: 'a'}

Replace items() with iteritems() if you're using Python 2.

这篇关于将函数应用于 Python 字典的所有键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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