我有这样的功能:
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/