Details of differences between defaultdict and dict in Python

  • 2021-12-13 08:33:28
  • OfStack

Catalog 1. Problem Description 2. Solution 3. Conclusion

This article is transferred from WeChat official account: "Beauty of Algorithm and Programming",

1. Description of the problem

In collections In the module defauldict When used with dict What's the difference? Why do we use dict In key An error is reported when the value does not exist, and defaudict No error will be reported, and the answer will be given below.

2. Solutions

To solve the problems encountered and solve them.

Code example:


import collections

// Quote collections Module 

dic=collections.defaultdict(int)

// Take advantage of the defauldict Definition 1 A dictionary 

for num in range(10):

dic[num]+=1

// Assign a value to a dictionary 

print(dic) 

Output:

defaultdict( < class 'int' > , {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1})

You can see from the code that the reference collections In the module defauldict() Property, defines a dictionary, assigns values to the dictionary and adds key values. It can be seen that at first dic No key Value, the dictionary returns a value of 1; In the same way, if you use it directly, dict What will be the result?

Code example:


dic=dict()

// Definition 1 A dictionary 

for num in range(10):

dic[num]+=1

// Assignment 

print(dic)

Output:

Exception occurred: KeyError

0

File "C:\ Users\ Hasee\ Desktop\ where2go-python-test\ 1906101031 Wang Zhuoyue\ Class\ ce_shi. py", line 81, in < module > dic[num]+=1

However, the output will report an error, which is caused by the dic() The corresponding one cannot be found in the key Value, that is, in the defined dic Can't be found in num Value, but the if conditional statement can also be used to achieve the same value as the defaultdict() 1-like effect.

Code example:


dic=dict()

for num in range(10):

    if num not in dic:

        dic[num]=0

// When dic Does not exist in num This key Value, add the num And assigned to 0

    dic[num]+=1

print(dic)

Output:

{0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1}

3. Conclusion

Through the above codes and results, we know that when defining 1 dictionary, there is no corresponding key Value, defauldict() This key value is added to the dictionary and assigned to 0, while using dict () directly to define it will report an error: the corresponding one cannot be found key Value. However, using if statement to actively assign values to key can also achieve defaultdict() 1-like effect.


Related articles: