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 defaultdict
s?