Using the default behavior of the dictionary

  • 2020-06-01 10:13:05
  • OfStack

This article is about the default behavior of Python using the dictionary, which is Shared for your reference and learning. Here is the detailed introduction:

Typical code 1:


from collections import defaultdict 
 
 
if __name__ == '__main__': 
 data = defaultdict(int) 
 data[0] += 1 
 print(data) 

Output 1:


defaultdict(<type 'int'>, {0: 1}) 

Typical code 2:


if __name__ == '__main__': 
 data = {'k': 1} 
 data.setdefault('k', 100) 
 data.setdefault('k1', -100) 
 print(data) 

Output 2:


{'k': 1, 'k1': -100} 

Application scenarios:

Typical application scenarios of code 1:

When writing code 1 some statistics, always need to statistics the number of 1 some key, use a dictionary to store the counting result, if you are using the classic dictionary, so every time we need artificial write code to determine the corresponding key exists, if there is no need to be stored in the dictionary, it initialized to 0; With the defaultdict data type, we can directly specify a factory function to produce the default value for us. Typical code 1 USES the built-in int function, but it can also be an anonymous function defined by the lambda expression.

Typical code 2 application scenarios:

For a dictionary, if we only want to keep the value of key specified the first time, if we use the traditional method data['k']='v', we need to check whether the corresponding key already exists in the dictionary every time, and then we can decide whether we can set the value of key. Using dict's setdefault method, we can avoid this judgment and implement this functionality in a more concise way.

Benefits:

1. The setdefault method in scenario 2, optimized in the implementation of the Python interpreter, is generally more efficient than the Python code you wrote with the same functionality

2. Both of these default scenarios make the code more compact and logically more efficient to read

Other instructions:

1. defaultdict type, which can receive many types, built-in list, set, dict can be directly used, lambda anonymous function can be used, you can use the type defined by yourself

conclusion


Related articles: