2

I want to use a defaultdict for simple string conversions. Basically converting some internal strings to more user friendly ones for the UI. However some of the strings are perfectly readable as is, and I'd prefer to only manually specify the ones that need to be converted. So I tried setting up a default dict with a lambda:

>>> dict = defaultdict(lambda key: key)
>>> dict["key"]
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    dict["key"]
TypeError: <lambda>() takes exactly 1 argument (0 given)
>>> dict = defaultdict(lambda: key)
>>> dict["key"]

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    dict["key"]
  File "<pyshell#4>", line 1, in <lambda>
    dict = defaultdict(lambda: key)
NameError: global name 'key' is not defined

So it seems a simple lambda wont solve this. Is there any way to access this directly? There are work arounds in that I could use get:

value = dict.get(key) or key
value = dict.get(key, key)

But I was hoping for something less verbose, and I could see future applications for this (eg. if every value should be based on a key calculation). Is it possible or am I just misusing defaultdicts?

SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
  • 1
    Duplicate of http://stackoverflow.com/q/2912231/2301450 – vaultah Nov 13 '15 at 15:34
  • 2
    What's wrong with `value = dict.get(key, key)`? If you want less verbose than that, maybe a custom dict subclass can help. – tobias_k Nov 13 '15 at 15:34
  • 1
    @vaultah Actually that answers my question entirely, it outright says that no information is passed to the function so I'd have to subclass `defaultdict` (as shown in that answer). – SuperBiasedMan Nov 13 '15 at 15:36

0 Answers0