Mapping over values in a python dictionary

后端 未结 7 1716
旧时难觅i
旧时难觅i 2020-11-27 09:49

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 an

7条回答
  •  旧时难觅i
    2020-11-27 10:26

    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 kv: (kv[0], f(kv[1])), my_dictionary.iteritems()))
    

    but that's not that readable, really.

提交回复
热议问题