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']
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With