I have a function of the sort:
def GetMapping(mappings, key):
mapping = mappings.get(key)
if mapping is None:
currentMax = mappings.get("max", 0)
mapping = currentMax + 1
mappings["max"] = mapping
mappings[key] = mapping
return mapping, mappings
Basically, given a dictionary mappings
and a key key
, the function returns the value associated to the key if this exists.
If not, it finds the current maximum id in the dictionary, stored under the key 'max', assigns it to this key, and updates the value of max.
I was wondering if there was a built-in/less verbose way of achieving this?
You can subclass dict
and override the __missing__
method.
class CustomMapping(dict):
def __missing__(self, key):
self[key] = self['max'] = self.get('max', 0) + 1
return self[key]
d = CustomMapping()
d['a'] # 1
d['b'] # 2
d['a'] # 1
d # {'a': 1, 'b': 2, 'max': 2}
As @Code-Apprentice points out it would be better to set a max
attribute in the __init__
method. This avoids a potential key collision (i.e. a key that happens to be named "max"
).
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