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

2024-09-30 02:21:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个函数:

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

基本上,给定一个字典mappings和一个键key,函数返回与键相关的值(如果存在)。你知道吗

如果没有,它将在字典中查找存储在键“max”下的当前最大id,将其分配给该键,并更新max的值

我想知道是否有一个内置的/不那么冗长的方式来实现这一点?你知道吗


Tags: key函数noneidgetreturnif字典
2条回答

您可以将dict子类化并重写^{}方法。你知道吗

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}

正如@Code学徒指出的,最好在__init__方法中设置一个max属性。这避免了潜在的密钥冲突(即,恰好命名为"max"的密钥)。你知道吗

假设您实际上不需要/想要一个可以从外部控制的'max'项,而只需要自动递增的id:

    defaultdict(count(1).next)

演示:

>>> from collections import defaultdict
>>> from itertools import count
>>> d = defaultdict(count(1).next)
>>> d['foo']
1
>>> d['bar']
2
>>> d['qux']
3
>>> d['foo']
1

相关问题 更多 >

    热门问题