Search code examples
pythondictionarydefaultdict

Python dictionary that defaults to key?


Is there a way to get a defaultdict to return the key by default? Or some data structure with equivalent behavior? I.e., after initializing dictionary d,

>>> d['a'] = 1
>>> d['a']
1
>>> d['b']
'b'
>>> d['c']
'c'

I've only seen default dictionaries take functions that don't take parameters, so I'm not sure if there's a solution other than creating a new kind of dictionary .


Solution

  • I'd override the __missing__ method of dict:

    >>> class MyDefaultDict(dict):
    ...     def __missing__(self, key):
    ...         self[key] = key
    ...         return key
    ...
    >>> d = MyDefaultDict()
    >>> d['joe']
    'joe'
    >>> d
    {'joe': 'joe'}