Python中defaultdict的使用
今天的文章讨论 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 作为默认值。
相关文章
Pandas DataFrame DataFrame.shift() 函数
发布时间:2024/04/24 浏览次数:133 分类:Python
-
DataFrame.shift() 函数是将 DataFrame 的索引按指定的周期数进行移位。
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
Pandas read_csv()函数
发布时间:2024/04/24 浏览次数:254 分类:Python
-
Pandas read_csv()函数将指定的逗号分隔值(csv)文件读取到 DataFrame 中。
Pandas 多列合并
发布时间:2024/04/24 浏览次数:628 分类:Python
-
本教程介绍了如何在 Pandas 中使用 DataFrame.merge()方法合并两个 DataFrames。
Pandas loc vs iloc
发布时间:2024/04/24 浏览次数:837 分类:Python
-
本教程介绍了如何使用 Python 中的 loc 和 iloc 从 Pandas DataFrame 中过滤数据。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串