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

标签 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

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

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

我想知道是否有一种内置/更简洁的方法来实现这一点?

最佳答案

您可以子类化 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}

正如@Code-Apprentice 指出的那样,最好在 __init__ 方法中设置一个 max 属性。这避免了潜在的键冲突(即碰巧命名为 "max" 的键)。

关于python - 自动更新键字典到整数映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48697047/

相关文章:

python - 从 C 导入标准 Python 库

python - nbconvert:ValueError:在以下路径中找不到名称为 'rst' 的模板子目录:[LS OF PATHS]

python - 是否可以让 python 打开一个终端并写入它?

python - 唯一列表(集)到字典

c++ - 用 <algorithm> 可以用 map 覆盖 map 吗?

python - 有没有一种快速的方法可以在 Python 中生成字母表的字典?

python - 使用 Twisted 更新共享数据

Python : Ensure string is exactly in A. B.C 格式 ..(两个点分隔 3 个字符串)

python - 与使用 Python 的 txt 文件中的列表相比,如何从 csv 文件中删除行?

python - 类型错误 : unsupported operand type(s) for *: 'dict' and 'int'