Mapping over values in a python dictionary

后端 未结 7 1565
旧时难觅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:50

    Just came accross this use case. I implemented gens's answer, adding a recursive approach for handling values that are also dicts:

    def mutate_dict_in_place(f, d):
        for k, v in d.iteritems():
            if isinstance(v, dict):
                mutate_dict_in_place(f, v)
            else:
                d[k] = f(v)
    
    # Exemple handy usage
    def utf8_everywhere(d):
        mutate_dict_in_place((
            lambda value:
                value.decode('utf-8')
                if isinstance(value, bytes)
                else value
            ),
            d
        )
    
    my_dict = {'a': b'byte1', 'b': {'c': b'byte2', 'd': b'byte3'}}
    utf8_everywhere(my_dict)
    print(my_dict)
    

    This can be useful when dealing with json or yaml files that encode strings as bytes in Python 2

    0 讨论(0)
提交回复
热议问题