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 .
Is it safe to use a frozenset as a dict key? Yes. According to the docs, Frozenset is hashable because it's immutable. This would imply that it can be used as the key to a dict, because the prerequisite for a key is that it is hashable.
These are things like integers, floats, strings, Booleans, functions. Even tuples can be a key. A dictionary or a list cannot be a key.
It turns out that in Python there is no good way to set a default value of a dictionary.
default defaults to None . Return the value for key if key is in the dictionary, else default . If default is not given, it defaults to None , so that this method never raises a KeyError .
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With