Python中defaultdict的使用

编程入门 行业动态 更新时间:2024-10-11 19:20:46

<a href=https://www.elefans.com/category/jswz/34/1770869.html style=Python中defaultdict的使用"/>

Python中defaultdict的使用

文章目录

    • Python 中的 defaultdict 与 dict
      • Python 中的 defaultdict
    • Python 中 defaultdict 的有用函数
      • Python 中的 defaultdict.clear()
      • Python 中的 defaultdict.copy()
      • Python 中的 defaultdict.default_factory()
      • Python 中的 defaultdict.get(key, default value)


今天的文章讨论 defaultdict 容器并使用代码示例演示其用法。


Python 中的 defaultdict 与 dict

defaultdict 是一个类似字典的容器,属于 collections 模块。 它是字典的子类; 因此它具有词典的所有功能。 然而,defaultdict 的唯一目的是处理 KeyError。

# return true if the defaultdict is a subclass of dict (dictionary)
from collections import defaultdict
print(issubclass(defaultdict,dict))

输出:

True

假设用户在字典中搜索条目,并且搜索到的条目不存在。 普通字典会出现KeyError,表示该条目不存在。 为了解决这个问题,Python 开发人员提出了 defaultdict 的概念。

代码示例:

# normal dictionary
ord_dict = {"x" :3,"y": 4
}ord_dict["z"]   # --> KeyError

输出:

KeyError: 'z'

普通字典无法处理未知键,当我们搜索未知键时,它会抛出 KeyError,如上面的代码所示。

另一方面,defaultdict 模块的工作方式与 Python 词典类似。 尽管如此,它仍然具有先进、有用且用户友好的功能,并且当用户在字典中搜索未定义的键时不会抛出错误。

相反,它在字典中创建一个条目,并针对该键返回一个默认值。 为了理解这个概念,让我们看看下面的实际部分。

代码示例:

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 创建我们尝试使用该键访问的任何项目,该键在字典中未定义。

并且创建这样一个默认项,它调用我们传递给defaultdict的构造函数的函数对象,更准确地说,该对象应该是一个包含类型对象和函数的可调用对象。

在上面的示例中,默认项是使用 def_val 函数创建的,该函数根据字典中未定义的键返回字符串“搜索到的键不存在”。

Python 中的 defaultdict

default_factory 是 __missing__() 方法使用的 defaultdict 构造函数的第一个参数,如果构造函数的参数丢失,default_factory 将被初始化为 None,这将出现 KeyError。

如果 default_factory 是用 None 以外的东西初始化的,它将被分配为搜索到的键的值,如上面的示例所示。


Python 中 defaultdict 的有用函数

字典和defaultdict有很多功能。 我们知道,defaultdict可以访问字典的所有功能; 然而,这些是 defaultdict 特有的一些最有用的函数。

Python 中的 defaultdict.clear()

代码示例:

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"] = 4print(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的值不再存在,这就是为什么我们得到的x和y不存在。

Python 中的 defaultdict.copy()

代码示例:

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"] = 4dic_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() 函数用于将字典的浅表副本复制到另一个我们可以相应使用的变量中。

Python 中的 defaultdict.default_factory()

代码示例:

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"] = 4print(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的值是函数返回的值。

Python 中的 defaultdict.get(key, default value)

代码示例:

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 作为默认值。

更多推荐

Python中defaultdict的使用

本文发布于:2023-12-03 21:17:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1657756.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Python   defaultdict

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!