python defaultdict

本文介绍了Python中defaultdict类的使用,它避免了KeyError,当键不存在时返回默认值。通过示例展示了defaultdict如何创建并设置默认值,包括使用函数、类以及基本类型作为默认值的情况。同时,解释了__missing__方法的作用和调用情况。
摘要由CSDN通过智能技术生成

Defaultdict in Python

介绍

在python里面,普通字典都是无序的,并且里面的元素都是独一无二的,一般情况下,我们使用字典的格式:
关键字必须是不变的类型,比如python的列表类型就不能是关键字,而tuple可以是关键字

dict1 = {'a':1,'b':2,'e':3,'d':4}
dict2 = {1:'a',2:[1,2],(1,2):'y'}
dict3 = {1:1, 2:4, 3:9}
print(dict1['b'])
print(dict2[2])
print(dict2[(1,2)])
print(dict3[2])
print(dict2['a'])

#结果
"""
2
[1, 2]
y
4

KeyError  Traceback (most recent call last)
<ipython-input-84-fac8e4c5aed0> in <module>
----> 1 print(dict2['a'])

KeyError: 'a'
"""
a = torch.tensor([1])
b = torch.tensor([2])
dict1 = {a:b}
print(dict1)
"""
{tensor([1]): tensor([2])}
"""

最后一个结果我们可以看到,如果元素不在字典里面,则会进行报错,
如果我们使用defaultdict来构建字典的话,即使元素不在字典内也不会报错,而是返回一个默认值。

from collections import defaultdict

def default_value():
    return 'Default_vale'
d = defaultdict(default_value)
d['a'] = 11
d['b'] = 12
print(d[3])
##结果
"""
Default_vale
"""
class Test(object):
    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b
    def maxs(self):
        return max(self.a, self.b)
    def mins(self):
        return min(self.a, self.b)
meters = defaultdict(Test)
meters['a'] = 1
print(meters['b'])
print(meters.__missing__('c'))

"""
<__main__.Test object at 0x7fbc3056cc10>
<__main__.Test object at 0x7fbc3056c880>

"""

__miss__:
defaultdict还有一个function,这个 函数是为字典提供默认值的
通过dict.__ miss __[k]获取设定的defaultvalue,它的参数是传入defaultdict(default_value),如果在设定defaultdict()里面没有传入default_value这个函数,那么KeyError会发生。
这个方法在需要的key没有找到的时候被dict类的 __ getitem __调用
由 __ getitem 来raise或者返回由 miss __返回的默认值

from collections import defaultdict
  
      
# Defining the dict
d = defaultdict(lambda: "Not Present")
d["a"] = 1
d["b"] = 2

d2 = defaultdict()
d2['a'] = 3
d2['b'] = 4
print(d.__missing__("a"))
print(d.__missing__('b'))
print(d.__missing__('d'))
print(d.__missing__('c'))
print(d2.__missing__('b'))
print(d2.__missing__('c'))

"""
Not Present
Not Present
Not Present
Not Present
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-92-14b17ade75ee> in <module>
     13 print(d.__missing__('d'))
     14 print(d.__missing__('c'))
---> 15 print(d2.__missing__('b'))

KeyError: 'b'

"""

如果传入defaultdict的类型为:list,int,set,str等等,而如果找不到k的时候返回的是对应的默认值,例如:list:[], int:0, str: ‘’, set: set()

dict1 = defaultdict(int)
dict2 = defaultdict(set)
dict3 = defaultdict(str)
dict4 = defaultdict(list)
dict4['a'].append('s')
dict4['b'] = 'x'
print(dict1[1])
print(dict2[1])
print(dict3[1])
print(dict4[1])
print(dict4)
"""
0
set()

[]
defaultdict(<class 'list'>, {1: [], 'a': ['s'], 'b': 'x'})
"""
d = defaultdict(list)
d1 = defaultdict(int)
L = [1, 2, 3, 4, 2, 4, 1, 2]
for i in range(5):
    d[i].append(i)
for i in L:
    d1[i] += 1
print(d)
print(d1)
"""
defaultdict(<class 'list'>, {0: [0], 1: [1], 2: [2], 3: [3], 4: [4]})
defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})
"""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值