'Create a defaultdict who's key refers to the same numerical value as the key

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 1:[1]

You can just create your own dict class and modify the __getitem__ method like this:

class mydict(dict):
    def __getitem__(self, x):
        if x not in self:
            return x
        else:
            return super().__getitem__(x)

This class has the behavior you want

>>> d = mydict()
>>> d[3]
3
>>> d[1.1]
1.1
>>> d[5] = -2
>>> d[5]
-2

EDIT: if you want the defaultdict behavior of adding the missing key to the dictionary, you can do this like so:

class mydict(dict):
    def __getitem__(self, x):
        if x not in self:
            self[x] = x
            return x
        else:
            return super().__getitem__(x)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1