Python 3 collections. defaultdict () and dict usage and Difference

Source: Internet
Author: User

In python, there is a module collections, which is interpreted as a data-type container module. A collections. defaultdict () is frequently used. Let's talk about this.

 

Summary:

HereDefaultdict (function_factory)Build a similarDictionary, WhereKeysValue, which is determined by yourself,ValuesIsFunction_factoryAnd has the default value. For exampleDefault (INT)CreateDictionaryObject, anyValuesAllIntAnd even if it does not existKey,D [Key]There is also a default value, which isINT ()The default value is 0.

 

Defaultdict
Dict subclass that calla factory function to supply missing values.

This is a brief explanation.

Defaultdict is a subclass of the built-in function dict. It calls the factory function to provide missing values.

 

Dizzy. What is a factory function:

Explanation from Python core programming

 

Python 2.2 unifies the types and classes, and all built-in types are classes now. On this basis, the original
The so-called built-in conversion functions, such as int (), type (), list (), and so on, have now become factory functions. That is to say, although
They look a little like a function. They are actually classes. When you call them, an instance of this type is actually generated.
For example, it is like producing goods in a factory.
The following familiar factory functions are called built-in functions in the old Python version:
INT (), long (), float (), complex ()
STR (), Unicode (), basestring ()
List (), tuple ()
Type ()
There were no other types of factory functions in the past, and now there are also factory functions. In addition, classes that support new styles
And the corresponding factory functions are added. These factory functions are listed below:
Dict ()
Bool ()
Set (), frozenset ()
Object ()
Classmethod ()
Staticmethod ()
Super ()
Property ()
File ()

 

Let's take a look at its usage:

  Import   collectionss  = [( '  yellow   ', 1), ( '  blue   ', 2), ('   yellow   ', 3), ( '  blue   ', 4), ('   Red   ', 1 )] d  =  collections. defaultdict (list)   for  K, v  in   S: d [K]. append (v) List (D. items ()  

 

Here, I started to understand that defaultdict can use a built-in function list as a parameter. In fact, list () itself is a built-in function, but after updating, everything in python is an object, so list is adapted into a class, and a class instance is generated when list is introduced.

 

I still don't quite understand. Let's look at defaultdict's help explanation.

Class Collections. Defaultdict ([ Default_factory[, ...] )

Returns a new dictionary-like object.DefaultdictIs a subclass of the built-inDictClass. It overrides one method and adds one writable instance variable. The remaining functionality is the same as forDictClass and is not supported ented here.

First, collections. defaultdict will return a dictionary-like object. Note that similar objects are not identical. The defaultdict and dict classes are almost the same, except that they overload a method and add a writable instance variable. (I still don't understand writable instance variables)

 

The first argument provides the initial value forDefault_factoryAttribute; It defaultsNone. All remaining arguments are treated the same as if they were passed toDictConstructor, including keyword arguments.

DefaultdictObjects support the following method in addition to the standardDictOPERATIONS:

_ Missing __ ( Key )

IfDefault_factoryAttribute isNone, This raisesKeyerrorException withKeyAs argument.

IfDefault_factoryIs notNone, It is called without arguments to provide a default value for the givenKey, This value is inserted in the dictionary forKey, And returned.

Pay attention to this. If default_factory is not none, the default_factory will be called in the form of no parameters and a key with the default value of ___ missing _ is provided. This default value is inserted into the data dictionary as the key and then returned.

Very dizzy. There is a _ missing _ method. The _ missing _ method is the built-in method of collections. defaultdict.

If callingDefault_factoryRaises an exception this exception is propagated unchanged.

This method is called by_ Getitem __()Method ofDictClass when the requested key is not found; whatever it returns or raises is then returned or raised_ Getitem __().

Note that_ Missing __()IsNotCalled for any operations besides_ Getitem __(). This means thatGet ()Will, like normal dictionaries, returnNoneAs a default rather than usingDefault_factory.

DefaultdictObjects support the following instance variable:

Default_factory

This attribute is used by_ Missing __()Method; it is initialized from the first argument to the constructor, if present, orNone, If absent.

 

It seems that this document is hard to understand. For example:

 Import Collectionss = [( '  Yellow  ' , 1 ),( '  Blue  ' , 2 ),( '  Yellow  ' , 3 ),( '  Blue  ' , 4 ),( '  Red  ' , 1)]  #  Defaultdict D = Collections. defaultdict (list)  For K, V In  S: d [K]. append (V)  #  Use dict and setdefault G = {}  For K, V In  S: G. setdefault (K, []). append (V)  #  Use dict E = {}  For K, V In  S: E [k] = V  #  # List (D. Items ())  #  # List (G. Items ())  #  # List (E. Items ()) 

 

View results

 List (D. Items ())[(  '  Blue  ' , [2, 4]), ('  Red  ' , [1]), ( '  Yellow  ' , [1, 3 ])] >>> List (G. Items ())[(  '  Blue  ' , [2, 4]), ( '  Red  ' , [1]), ( '  Yellow ' , [1, 3 ])] >>> List (E. Items ())[(  '  Blue  ' , 4 ),( '  Red  ' , 1 ),( '  Yellow  ' , 3 )] >>> Ddefaultdict ( < Class  '  List  ' > ,{ '  Blue  ' : [2, 4], '  Red  ' : [1], '  Yellow  ' : [1, 3 ]}) >>> G {  '  Blue ' : [2, 4], '  Red  ' : [1], '  Yellow  ' : [1, 3 ]} >>> E {  '  Blue  ' : 4, '  Red  ' : 1, ' Yellow  ' : 3 } >>> D. Items () dict_items ([(  '  Blue  ' , [2, 4]), ( '  Red  ' , [1]), ( '  Yellow  ' , [1, 3 ]) >>> D [ " Blue  "  ] [ 2, 4 ] >>> D. Keys () dict_keys ([  '  Blue  ' , '  Red  ' , '  Yellow  '  ]) >>> D. default_factory <Class   '  List  ' >>>> D. Values () dict_values ([[ 2, 4], [1], [1, 3])

We can see that

Collections. defaultdict (list) is similar to dict. setdefault ().

This is also true for python help.

When each key is encountered for the first time, it is not already in the mapping; so an entry is automatically created usingDefault_factoryFunction which returns an emptyList.List. append ()Operation then attaches the value to the new list. When keys are encountered again, the look-up proceeds normally (returning the list for that key) andList. append ()Operation adds another value to the list. This technique is simpler and faster than equivalent technique usingDict. setdefault ():

 

This method is equivalent to dict. setdefault (), but faster.

It is necessary to look at dict. setdefault ()

Setdefault ( Key[, Default] )

IfKeyIs in the dictionary, return its value. If not, insertKeyWith a valueDefaultAnd returnDefault.DefaultDefaultsNone.

If the key already exists in dictionary, return value. If the key does not exist, insert the key and a default value, and return default. The default ults is none.

 

However, it should be noted that defaultdict is equivalent to dict. setdefault, which is different from the direct value assignment below. As you can see from the results, the direct value assignment will overwrite.

 

From the end of D. Values and D ["blue"], the subsequent use is actually the same as that of dict. The only difference is the initialization problem. Defaultdict can use the factory function to bring a default value to the initial keyi.

This default value may be an empty list [] defaultdict (list), maybe 0, defaultdict (INT ).

 

Let's take a look at the example below.

Defaultdict (INT) Where d actually generates a data dictionary with a key whose default value is 0. You can imagine d [Key] = int default (the default value of the int factory function is 0)

 

D [K], so you can directly read d ["M"] + = 1 is d ["M"] is the default value 0 + 1 = 1

The same is true.

 

>>> S =  '  Mississippi   ' d =  defaultdict (INT)   for  K  in   S :... d [k] + = 1 ... >>>  List (D. items () [(  '  I   ', 4), ( '  P   ', 2), ('   S   ', 4), ( '  m   ', 1)] 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.