在以前我们使用dict的时候, 如果访问不存在的key时会抛出异常. 使用defaultdict则可以避免这个问题.

defaultdict(函数)

说明:

  1. 如果访问的key不存在, 则会调用传递的函数, 把函数作为value

  2. 其余的使用和dict一样

from collections import defaultdict

d = defaultdict(lambda: "默认值")
d["b"] = "bbb"
# key 不存在, 则调用函数, 把函数返回值作为值. 并把键值对存入到 defaultdict中
print(d["a"])    
print(d["b"])
print(d)


from collections import defaultdict

s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

d = defaultdict(list)
for k, v in s:
    d[k].append(v)


print(sorted(d.items()))


from collections import defaultdict
# 统计每个字符出现的次数
s = "abcdabAbc"

d = defaultdict(int)
for k in s:
    d[k] += 1


print(sorted(d.items()))

Copyright © 李振超 2018 all right reserved,powered by Gitbook
该文件最后修订时间: 2018-02-25 07:12:09

results matching ""

    No results matching ""