Python dictionary that defaults to key?
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'}
Edit: Oops, I just realized that code in my file originally came from another stackoverflow answer! https://stackoverflow.com/a/2912455/456876, go upvote that one.
This is what I use - it's a defaultdict variant that passes the key as an argument to the default-value factory function that's passed as an argument to init, instead of no arguments:
class keybased_defaultdict(defaultdict): def __missing__(self, key): if self.default_factory is None: raise KeyError(key) else: value = self[key] = self.default_factory(key) return value
This is the use you want:
>>> d = keybased_defaultdict(lambda x: x)>>> d[1]1>>> d['a']'a'
Other possibilities:
>>> d = keybased_defaultdict(lambda x: len(x))>>> d['a']1>>> d['abc']3
If you don't want to subclass dict, you can try using
d.get('a', 'a')d.get('b', 'b')d.get('c', 'c')
Which I think is clearer and less magical for this purpose
If you are a DRY fanatic and only have single char keys, you can do this :)
d.get(*'a'*2)d.get(*'b'*2)d.get(*'c'*2)