当前位置: 首页 > news >正文

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

http://www.lryc.cn/news/204478.html

相关文章:

  • 【ccc3.8】虚拟列表
  • 【23种设计模式】单一职责原则
  • DNS入门学习:什么是TTL值?如何设置合适的TTL值?
  • ilr normalize isometric log-ratio transformation
  • el表单的简单查询方法
  • 【USRP】通信总的分支有哪些
  • 关于服务器网络代理解决方案(1024)
  • Linux下 /etc/shadow内容详解
  • Go学习第二章——变量与数据类型
  • 【剑指Offer】:循环有序列表的插入(涉及链表的知识)
  • 【Django 04】Django-DRF(ModelViewSet)
  • ubuntu命令
  • C++学习之强制类型转换
  • 在Linux中,可以使用以下命令来查看进程
  • 【算法训练-动态规划 一】【应用DP问题】零钱兑换、爬楼梯、买卖股票的最佳时机I、打家劫舍
  • 2023年中职组“网络安全”赛项云南省竞赛任务书
  • Modeling Deep Learning Accelerator Enabled GPUs
  • 《动手学深度学习 Pytorch版》 9.5 机器翻译与数据集
  • 网络入门基础
  • Towards a Rigorous Evaluation of Time-series Anomaly Detection(论文翻译)
  • 理解Python装饰器
  • VR智慧景区,为游客开启智慧旅游新时代
  • 蓝桥杯 Java 青蛙过河
  • 雷达图应该如何去绘制?
  • 1024 蓝屏漏洞攻防战(第十九课)
  • 短视频矩阵系统软件源码
  • 内网穿透的应用-如何通过TortoiseSVN+内网穿透,实现公网提交文件到内网SVN服务器?
  • 有没有PC端的配音软件推荐?(免下载)
  • clickhouse
  • linux下创建文件夹软链接