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

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

问题描述

给定一个字典 {k1:v1,k2:v2 ...} 我想要得到 {k1:f(v1),k2 :f(v2)...} 如果我传递函数 f



有没有这样的内置功能?或者我需要在my_dictionary中为(k,v)执行

  dict([(k,f(v) iteritems()])

理想情况下,我会写

  my_dictionary.map_values(f)

  my_dictionary.mutate_values_with(f)

也就是说,如果原始字典被突变或创建了副本,这并不重要。

解决方案

没有这样的功能;这样做的最简单的方法是使用字母理解:

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

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



请注意,列表上没有这样的方法;您必须使用列表解析或 map()函数。



因此,您可以使用

  my_dictionary的 map()函数= dict(map(lambda(k,v):(k,f(v)),my_dictionary.iteritems()))

但这不是可读的,真的。


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

Ideally I would just write

my_dictionary.map_values(f)

or

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

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.

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

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

my_dictionary = dict(map(lambda (k,v): (k, f(v)), my_dictionary.iteritems()))

but that's not that readable, really.

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

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