在Python中使用defaultdict
今天的文章讨论了defaultdict
容器,并使用代码实例演示了它的使用。
defaultdict
VS Python中的dict
defaultdict
是一个像 dictionary 一样的容器,属于 collections 模块。它是 dictionary 的一个子类;因此它具有dictionary
的所有功能。然而,defaultdict
的唯一目的是处理KeyError
。
# return true if the defaultdict is a subclass of dict (dictionary)
from collections import defaultdict
print(issubclass(defaultdict,dict))
输出:
True
假设一个用户在dictionary
中搜索一个条目,而搜索到的条目不存在。普通字典会出现一个KeyError
,这意味着该条目不存在。为了克服这个问题,Python开发者提出了defaultdict
的概念。
代码示例:
# normal dictionary
ord_dict = {
"x" :3,
"y": 4
}
ord_dict["z"] # --> KeyError
输出:
KeyError: 'z'
普通字典不能处理未知的keys
,当我们搜索一个未知的key
时,它会抛出KeyError
,如上面的代码所示。
另一方面,defaultdict
模块的工作方式与 Python 字典类似。尽管如此,它还是有先进的、有用的和用户友好的功能,当用户在字典中搜索一个未定义的键时,它不会抛出一个错误。
而是在字典中创建一个条目,并针对key
返回一个默认值。为了理解这个概念,让我们看看下面的实际部分。
代码示例:
from collections import defaultdict
# the default value for the undefined key
def def_val():
return "The searched Key Not Present"
dic = defaultdict(def_val)
dic["x"] = 3
dic["y"] = 4
# search 'z' in the dictionary 'dic'
print(dic["z"]) # instead of a KeyError, it has returned the default value
print(dic.items())
输出:
The searched Key Not Present
dict_items([('x', 3), ('y', 4), ('z', 'The searched Key Not Present')])
defaultdict
创建任何我们试图用键来访问的项目,这个键在字典中是未定义的。
并创建这样的default
项目,它调用我们传递给defaultdict
构造函数的函数对象,更准确地说,这个对象应该是一个callable
对象,包括类型对象和函数。
在上面的例子中,默认项是用def_val
函数创建的,它针对字典中未定义的键返回一个字符串The searched Key Not Present
。
Python 中的defaultdict
default_factory
是defaultdict
构造函数的第一个参数,它被__missing__()
方法使用,如果构造函数的参数缺失,default_factory
将被初始化为None
,这将产生KeyError
。
如果default_factory
的初始化参数不是None
,它将被分配为value
,并被搜索到key
,如上面的例子所示。
Python中defaultdict
的有用函数
有大量的dictionary
和defaultdict
的函数。正如我们所知,defaultdict
可以访问dictionary
的所有函数;然而,这些是一些专门针对defaultdict
的最有用的函数。
defaultdict.clear()
在Python中
代码示例:
from collections import defaultdict
# the default value for the undefined key
def def_val():
return "Not Present"
dic = defaultdict(def_val)
dic["x"] = 3
dic["y"] = 4
print(f'Before clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}')
dic.clear() #dic.clear() -> None. it will remove all items from dic.
print(f'After clearing the dic, values of x = {dic["x"]} and y = {dic["y"]}')
输出:
Before clearing the dic, values of x = 3 and y = 4
After clearing the dic, values of x = Not Present and y = Not Present
正如我们在上面的例子中看到的,我们在字典dic
中有两对数据,其中x=3
和y=4
。然而,在使用clear()
函数后,数据被删除了,x
和y
的值不存在了,这就是为什么我们得到Not present
对抗x
和y
。
defaultdict.copy()
在Python中
代码示例:
from collections import defaultdict
# the default value for the undefined key
def def_val():
return "Not Present"
dic = defaultdict(def_val)
dic["x"] = 3
dic["y"] = 4
dic_copy = dic.copy() # dic.copy will give you a shallow copy of dic.
print(f"dic = {dic.items()}")
print(f"dic_copy = {dic_copy.items()}")
输出:
dic = dict_items([('x', 3), ('y', 4)])
dic_copy = dict_items([('x', 3), ('y', 4)])
defaultdict.copy()
函数用于将字典的浅层拷贝到另一个变量中,我们可以相应地使用。
defaultdict.default_factory()
在Python中
代码示例:
from collections import defaultdict
# the default value for the undefined key
def def_val():
return "Not present"
dic = defaultdict(def_val)
dic["x"] = 3
dic["y"] = 4
print(f"The value of z = {dic['Z']}")
print(dic.default_factory()) # default_factory returns the default value for defaultdict.
输出:
The value of z = Not present
Not present
default_factory()
函数用于为定义的类的属性提供默认值,一般来说,default_factory
的值是由函数返回的值。
defaultdict.get(key, default value)
在Python中
代码示例:
from collections import defaultdict
# the default value for the undefined key
def def_val():
return "Not present"
dic = defaultdict(def_val)
dic["x"] = 3
dic["y"] = 4
# search the value of Z in the dictionary dic; if it exists, return the value; otherwise, display the message
print(dic.get("Z","Value doesn't exist")) # default value is None
输出:
Value doesn't exist
defaultdict.get()
函数需要两个参数,第一个是键,第二个是针对键的默认值,以防该值不存在。
但是第二个参数是可选的。所以我们可以指定任何信息或值;否则,它将显示None
作为默认值。