在 python 字典中映射值 [英] Mapping over values in a python dictionary

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

问题描述

给定字典 { k1: v1, k2: v2 ... } 我想得到 { k1: f(v1), k2: f(v2) ... } 前提是我传递了一个函数 f.

Given a dictionary { k1: v1, k2: v2 ... } I want to get { k1: f(v1), k2: f(v2) ... } provided I pass a function f.

有没有这样的内置函数?还是我必须要做

Is there any such built in function? Or do I have to do

dict([(k, f(v)) for (k, v) in my_dictionary.iteritems()])

理想情况下我会写

my_dictionary.map_values(f)

my_dictionary.mutate_values_with(f)

也就是说,原始字典是否发生变异或创建副本对我来说无关紧要.

That is, it doesn't matter to me if the original dictionary is mutated or a copy is created.

推荐答案

没有这个功能;最简单的方法是使用字典理解:

There is no such function; the easiest way to do this is to use a dict comprehension:

my_dictionary = {k: f(v) for k, v in my_dictionary.items()}

在 python 2.7 中,使用 .iteritems() 方法而不是 .items() 来节省内存.dict comprehension 语法直到 python 2.7 才被引入.

In python 2.7, use the .iteritems() method instead of .items() to save memory. The dict comprehension syntax wasn't introduced until python 2.7.

注意列表中也没有这样的方法;您必须使用列表推导式或 map() 函数.

Note that there is no such method on lists either; you'd have to use a list comprehension or the map() function.

因此,您也可以使用 map() 函数来处理您的字典:

As such, you could use the map() function for processing your dict as well:

my_dictionary = dict(map(lambda kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))

但这不是那么可读,真的.

but that's not that readable, really.

这篇关于在 python 字典中映射值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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