Mapping over values in a python dictionary

后端 未结 7 1672
旧时难觅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条回答
  •  眼角桃花
    2020-11-27 10:49

    You can do this in-place, rather than create a new dict, which may be preferable for large dictionaries (if you do not need a copy).

    def mutate_dict(f,d):
        for k, v in d.iteritems():
            d[k] = f(v)
    
    my_dictionary = {'a':1, 'b':2}
    mutate_dict(lambda x: x+1, my_dictionary)
    

    results in my_dictionary containing:

    {'a': 2, 'b': 3}
    

提交回复
热议问题