Mapping over values in a python dictionary

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

    While my original answer missed the point (by trying to solve this problem with the solution to Accessing key in factory of defaultdict), I have reworked it to propose an actual solution to the present question.

    Here it is:

    class walkableDict(dict):
      def walk(self, callback):
        try:
          for key in self:
            self[key] = callback(self[key])
        except TypeError:
          return False
        return True
    

    Usage:

    >>> d = walkableDict({ k1: v1, k2: v2 ... })
    >>> d.walk(f)
    

    The idea is to subclass the original dict to give it the desired functionality: "mapping" a function over all the values.

    The plus point is that this dictionary can be used to store the original data as if it was a dict, while transforming any data on request with a callback.

    Of course, feel free to name the class and the function the way you want (the name chosen in this answer is inspired by PHP's array_walk() function).

    Note: Neither the try-except block nor the return statements are mandatory for the functionality, they are there to further mimic the behavior of the PHP's array_walk.

提交回复
热议问题