其他分享
首页 > 其他分享> > defaultdict高级用法

defaultdict高级用法

作者:互联网

说明

defaultdict数据结构允许调用者提供一个函数,用来在键名缺失的情况下,创建与这个
键对应的值。只要字典发现调用者想要访问的键不存在,就会触发这个函数,以返回应该
与键相关联的默认值

下面定义一个log_missing函数作为键名缺失时的挂钩,该函数总是会把这种键的默认值设为0。

def log_missing():
  print("Key added")
  return 0

下面这段代码通过定制的defaultdict字典,把increments列表里面描述的增量添加到current
这个普通字典所提供的初始量上面,但字典里一开始没有'red'和'orange'这两个键,因此
log_missing这个挂钩函数会触发两次,每次它都会打印'Key added'信息。

from collections import defaultdict
current = {'green': 12, 'blue': 3}
increments = [
  ('red', 5),
  ('blue', 17),
  ('orange', 9),
]
result = defaultdict(log_missing, current) # 2个参数的用法,参数1表示自定义的函数,参数2表示在current中存在的key将跳过,不在current中的key将添加默认值0(log_missing返回值)
print('Before:', dict(result))
for key, amount in increments:
  result[key] += amount
print('After:', dict(result))

>>>
Before: {'green': 12, 'blue': 3}
Key added
Key added
After: {'green': 12, 'blue': 20, 'red': 5, 'orange': 9}

标签:defaultdict,log,missing,高级,用法,current,result,Key
来源: https://www.cnblogs.com/weiweivip666/p/16526963.html