Issue
I'm looking to create a defaultdict
who's key automatically refers to an integer or float of equal value
ie behavior would be:
In [1]: selfkey = defaultdict(something)
In [2]: selfkey[4]
Out[2]: 4
In [3]: selfkey[800]
Out[3]: 800
I'm not sure if this is possible and I'm also not sure if this is the same question here: Is there a clever way to pass the key to defaultdict's default_factory?
^I don't understand if the wording is asking for the same thing that I'm looking for.
I'd think there would be a recursive answer somehow but I'm not having any luck trying to implement a lambda function that can get the value to refer to itself.
The closest I've gotten is to refer back to the keys of the dict itself, but this extends itself when you pass a second value:
In [50]: t = defaultdict(lambda: t.keys())
In [51]: t[4]
Out[51]: dict_keys([4])
In [52]: t[5]
Out[52]: dict_keys([4, 5])
Any ideas?
Solution
Using the solution proposed in Is there a clever way to pass the key to defaultdict's default_factory?.
from collections import defaultdict
class keydefaultdict(defaultdict):
def __missing__(self, key):
if self.default_factory is None:
raise KeyError( key )
else:
ret = self[key] = self.default_factory(key)
return ret
d = keydefaultdict(lambda key: key)
print(d[4])
print(d[5])
This outputs
4
5
Answered By - scespinoza
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.