详解Python中defaultdict的具体使用

 更新时间:2023年10月25日 08:10:07   作者:迹忆客  
defaultdict 是一个类似字典的容器,属于 collections 模块, 它是字典的子类, 因此它具有词典的所有功能,下面小编就来和大家详细聊聊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"] = 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的值不再存在,这就是为什么我们得到的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"] = 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() 函数用于将字典的浅表副本复制到另一个我们可以相应使用的变量中。

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

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的具体使用的详细内容,更多关于python defaultdict的资料请关注脚本之家其它相关文章!

相关文章

  • Python实现图片指定位置加图片水印(附Pyinstaller打包exe)

    Python实现图片指定位置加图片水印(附Pyinstaller打包exe)

    这篇文章主要介绍了Python实现图片指定位置加图片水印,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • 用python画城市轮播地图

    用python画城市轮播地图

    轮播地图可以在很多方面有实际应用,所以就介绍给大家,并给出个实际操作案例,感兴趣的朋友可以参考下
    2021-05-05
  • pandas中的dataframe汇总和计算方法

    pandas中的dataframe汇总和计算方法

    这篇文章主要介绍了pandas中的dataframe汇总和计算方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • Python 文档解析lxml库的使用详解

    Python 文档解析lxml库的使用详解

    lxml 是 Python 常用的文档解析库,能够高效地解析 HTML/XML 文档,常用于 Python 爬虫,这篇文章主要介绍了Python 文档解析:lxml库的使用,需要的朋友可以参考下
    2022-09-09
  • Python大数据之使用lxml库解析html网页文件示例

    Python大数据之使用lxml库解析html网页文件示例

    这篇文章主要介绍了Python大数据之使用lxml库解析html网页文件,结合实例形式分析了Python大数据操作中使用lxml库解析html网页具体步骤及相关注意事项,需要的朋友可以参考下
    2019-11-11
  • Python中read,readline和readlines的区别案例详解

    Python中read,readline和readlines的区别案例详解

    这篇文章主要介绍了Python中read,readline和readlines的区别案例详解,本篇文章通过简要的案例,讲解了该项技术的了解与使用,以下就是详细内容,需要的朋友可以参考下
    2021-09-09
  • Python使用SQLAlchemy模块实现操作数据库

    Python使用SQLAlchemy模块实现操作数据库

    SQLAlchemy 是用Python编程语言开发的一个开源项目,它提供了SQL工具包和ORM对象关系映射工具,使用SQLAlchemy可以实现高效和高性能的数据库访问,下面我们就来学习一下SQLAlchemy模块的具体应用吧
    2023-11-11
  • python解决字符串倒序输出的问题

    python解决字符串倒序输出的问题

    今天小编就为大家分享一篇python解决字符串倒序输出的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-06-06
  • django 前端页面如何实现显示前N条数据

    django 前端页面如何实现显示前N条数据

    这篇文章主要介绍了django 前端页面如何实现显示前N条数据。具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • python+Django+apache的配置方法详解

    python+Django+apache的配置方法详解

    这篇文章主要介绍了python+Django+apache的配置方法,详细分析了python+Django+apache的安装与配置步骤,并分析了相关注意事项,具有一定参考借鉴价值,需要的朋友可以参考下
    2016-06-06

最新评论