您的位置:

Python 中的defaultdict

字典是 Python 中数据值的无序集合,用于存储数据值,如地图。字典保存键值对,而不是像其他数据类型一样保存单个值作为元素。字典中实现的键必须是唯一且不可变的。也就是说,Python 元组可以是关键字,但是 Python 列表不能是字典中的关键字。我们可以通过在花括号{}内放置一系列元素来创建字典,逗号“,”可以分隔值。

例 1:


Dict_1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
print ("Dictionary: ")
print (Dict_1)
print ("key pair 1: ", Dict_1[1])
print ("key pair 3: ", Dict_1[3])

输出:

Dictionary: 
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
key pair 1: A
key pair 3: C

但是如果我们试图打印第五个键值,那么我们会得到错误,因为“Dict _ 1”不包含第五个键值。

例 2:


Dict_1 = {1: 'A', 2: 'B', 3: 'C', 4: 'D'}
print ("Dictionary: ")
print (Dict_1)
print ("key pair 5: ", Dict_1[5])

输出:

Dictionary: 
{1: 'A', 2: 'B', 3: 'C', 4: 'D'}
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
 in <module>2 print ("Dictionary: ")
      3 print (Dict_1)
----> 4 print ("key pair 5: ", Dict_1[5])

KeyError: 5</module> 

每当键错误出现时,就可能成为用户的问题。我们可以通过使用 Python 的另一个字典来克服这个错误,它就像一个名为 Defaultdict 的容器。用户可以在“收藏”模块中找到这本字典。

defaultdict(预设字典)

defaultdict 是 Python 的字典,它就像一个容器,存在于“集合”模块中。它是字典类的一个子类,用于返回类似字典的对象。defaultdict 和字典具有相同的功能,除了 defaultdict 从不引发任何键错误,因为它为键提供了默认值,而该默认值不存在于用户创建的字典中。

语法:


defaultdict(default_factory)

参数:

  • default _ factory:default _ factory()函数返回用户为自己定义的字典设置的默认值。如果这个参数不存在,那么字典将引发键错误。

示例:


from collections import defaultdict as DD
# Function for returning a default values for the
# keys which are not present in the dictionary
def default_value():
    return "This key is not present"

# Now, we will define the dict
dict_1 = DD(default_value)
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key pair 1: ", dict_1["ABC"])
print ("key pair 3: ", dict_1["GHI"])
print ("key pair 5: ", dict_1["MNO"])

输出:

Dictionary: 
defaultdict(, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key pair 1:  1
key pair 3:  3
key pair 5:  This key is not present 

违约的内部运作

当我们使用 defaultdict 时,除了标准的字典操作之外,我们还获得了一个额外的可写实例变量和一个方法。可写实例变量是默认的 _factory 参数, missing 是方法。

  • default _ factory:default _ factory()函数返回用户为自己定义的字典设置的默认值。

示例:


from collections import defaultdict as DD
dict_1 = DD(lambda: "This key is not present")
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key value 1: ", dict_1["ABC"])
print ("key value 3: ", dict_1["GHI"])
print ("key value 5: ", dict_1["MNO"])

输出:

Dictionary: 
defaultdict( at 0x0000019EFC4B58B0>, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key value 1:  1
key value 3:  3
key value 5:  This key is not present 
  • missing (): missing ()函数用于为字典提供默认值。missing()函数将 default_factory 作为参数,如果该参数设置为 None,将引发 KeyError 否则,它将为给定的键提供默认值。当没有找到请求的密钥时,这个方法实际上是由 dict 类的 getitem() 函数调用的。getitem()函数提升或返回 missing()函数中的值。

示例:


from collections import defaultdict as DD
dict_1 = DD(lambda: "This key is not present")
dict_1["ABC"] = 1
dict_1["DEF"] = 2
dict_1["GHI"] = 3
dict_1["JKL"] = 4
print ("Dictionary: ")
print (dict_1)
print ("key value 1: ", dict_1.__missing__('ABC'))
print ("key value 4: ", dict_1["JKL"])
print ("key value 5: ", dict_1.__missing__('MNO'))

输出:

Dictionary: 
defaultdict( at 0x0000019EFC4B5670>, {'ABC': 1, 'DEF': 2, 'GHI': 3, 'JKL': 4})
key value 1:  This key is not present
key value 4:  4
key value 5:  This key is not present 

如何使用“列表”作为默认工厂

我们可以传递一个 list 类作为 default_factory 参数,它将使用以 list 格式设置的值创建一个 defaultdict。

示例:


from collections import defaultdict as DD
# Defining a dictionary
dict_1 = DD(list)

for k in range(7, 12):
    dict_1[k].append(k)

print ("Dictionary with values as list:")
print (dict_1)

输出:

Dictionary with values as list:
defaultdict(<class 'list'>, {7: [7], 8: [8], 9: [9], 10: [10], 11: [11]})

如何使用“int”作为默认工厂

我们可以将 int 类作为 default_factory 参数传递,它将创建一个默认值设置为零的 defaultdict。

示例:


from collections import defaultdict as DD

# Defining the dict
dict_1 = DD(int)

J = [1, 2, 3, 4, 2, 4, 1, 2]

# Now, we will iterate through the list "J"
# for keeping the count
for k in J:

    # As, The default value is 0
    # so we do not need to
    # enter the key first
    dict_1[k] += 1

print(dict_1)

输出:

defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2})

结论

在本教程中,我们讨论了 Python 中的 defaultdict,以及如何使用 default_factory 参数对 defaultdict 执行不同的操作。