自动更新键到整数映射的字典

MrD*_*MrD 4 python dictionary

我有一个类型的功能:

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
Run Code Online (Sandbox Code Playgroud)

基本上,给定字典mappings和键key,该函数返回与键相关联的值(如果存在).

如果没有,它会在字典中找到当前最大id,存储在键'max'下,将其分配给此键,并更新max的值.

我想知道是否有一种内置/不那么详细的方法来实现这一目标?

Ale*_*lex 7

您可以子类化dict并覆盖该__missing__方法.

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}
Run Code Online (Sandbox Code Playgroud)

正如@ Code-Apprentice指出的那样max,在__init__方法中设置属性会更好.这避免了潜在的密钥冲突(即恰好命名的密钥"max").