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

Viewed 776

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']
4 Answers

In addition to @Ronan-Paixão answer

  1. TransformDict was a hypergeneralization which sprang up out of wanting case-folding keys, but with no rigorous research into what real world users might need the generalization for --- meaning the user expectations of what it should do were not well thought through, as the original question illustrates.
  2. A recommendation is to implement your own dictionary subclass, to fit your own use case, as other answers have suggested.

So rather than suggesting "do not use TransformDict" I would suggest, "build your own, but give your class a better more descriptive name", then you'll know what it does, will have it quarantined, and not encourage bad stuff in the repos.

A good reference in addition to the PEP 455 is Hettinger's presentation: http://il.pycon.org/2016/static/sessions/raymond-hettinger.pdf

Related