Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically updated dictionary of keys to integer mappings

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?

like image 897
MrD Avatar asked Mar 06 '23 22:03

MrD


1 Answers

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").

like image 143
Alex Avatar answered Mar 17 '23 04:03

Alex