collections.defaultdict() dict 区别 使用 dict.get() python 使用场景

  • 1 普通字典
    首先,看看python里面的基础字典使用,下面代码会出错,因为字典里没有key值"k2"存在。
d = {
    
    "k1": 123}
print(d["k2"])

  • 2 普通字典的get()
    python里字典的get()方法获取key的value,如果没有key,返回默认项,默认项可以是任意对象。
    但是,get方法不会改变字典本身。
    下面的代码演示了这一原则。
d = {
    
    "k1": 123}
print(d.get('k2', 45))
print(d.get('k2', []))
print(d)

ouput:

45
[]
{'k1': 123}

  • 3 collections.defaultdict()

collections.defaultdict 在最初需要设置默认返回的对象,当找不到key时候,自动创建一个键值对到原字典,原字典会改变。

from collections import defaultdict

d = defaultdict(int)
d['k1'] = 123
print("普通的", d)

print(d['k2'])
print("查找了一个不存在的key后的d", d)

output

普通的 defaultdict(<class 'int'>, {'k1': 123})
0
查找了一个不存在的key后的d defaultdict(<class 'int'>, {'k1': 123, 'k2': 0})

  • 4 collections.defaultdict() 的应用场景

做一些数据统计的时候,比如直方图,统计每个类别有多少数量,开始也不知道有多少类别。
下面代码演示了这一场景,统计s字符串中各个字母的数量个数。

from collections import defaultdict

s = 'mississippi'

d = defaultdict(int)

for k in s:
    d[k] += 1

print(d.items())

output

dict_items([('m', 1), ('i', 4), ('s', 4), ('p', 2)])

猜你喜欢

转载自blog.csdn.net/x1131230123/article/details/114385116