Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Executing transform function on parameter dict when creating new transformdict

I've read about this cool new dictionary type, the transformdict

I want to use it in my project, by initializing a new transform dict with regular dict:

tran_d = TransformDict(str.lower, {'A':1, 'B':2})

which succeeds but when I run this:

tran_d.keys()

I get:

['A', 'B']

How would you suggest to execute the transform function on the parameter (regular) dict when creating the new transform dict? Just to be clear I want the following:

tran_d.keys() == ['a', 'b']
like image 388
NI6 Avatar asked Jul 09 '17 11:07

NI6


1 Answers

I already said it in the comments but it's important to realize that this is not what TransformDict is meant to do. Therefore you could subclass it with a custom implementation for keys:

class MyTransformDict(TransformDict):
    def keys(self):
        return map(self.transform_func, super().keys())

Depending on your Python version you probably need to use list() around the map (Python 3) or provide arguments for super: super(TransformDict, self) (Python 2). But it should illustrate the principle.

As @Rawing pointed out in the comments there will be more methods that don't work as expected, i.e. __iter__, items and probably also __repr__.

like image 192
MSeifert Avatar answered Sep 18 '22 23:09

MSeifert