Introduction to Python defaultdict types in the collections module

Source: Internet
Author: User
Tags python defaultdict

Here we introduce the usage of the defaultdict type in Python's collections module, the biggest difference from the built-in dictionary class is the initialization, and look at it together:

The defaultdict is primarily used in situations where value initialization is required. For a dictionary, key must be hashable,immutable,unique data, and value can be any data type. If value is a data type such as list,dict, it must be initialized to null before use, and some cases require that value be initialized to a special value, such as 0 or '.

From collections Import Defaultdictperson_by_age = Defaultdict (list) for person in persons:  d[person.age].append ( Person.name)

Defaultdict and Dict Use the same method, only when the initialization must pass in a callable object X, when accessing a key that does not exist, the value is automatically set to X (). For example, in the example above, when a person who first accesses a certain age d[person.age] will become a list (), that is, [].

Of course, you can also use your own defined callable objects, such as:

D = defaultdict (lambda:0) d["Hello"] + = 1     # 1d["a"]         # 0

Defaultdict is more efficient than dict.set_default and more intuitive and convenient to use.

The standard dictionary includes a method, SetDefault (), to get a value that establishes a default value if the value does not exist. Defaultdict initializing a container causes the caller to specify the default value in advance.

Import Collectionsdef default_factory ():  return ' default value ' d = collections.defaultdict (default_factory, foo = ' Bar ') print ' d: ', dprint ' foo = ', d[' foo ']print ' var = ', d[' bar]

You can use this method as long as all keys have the same default value.
The above results are:

D:defaultdict (<function default_factory at 0x0201fab0>, {' foo ': ' Bar '}) foo = Barvar + = default value


Other instances

1#Dic1 = {}2#dic1["K1"].append ("KKKKK") #正常情况会报错3#Print (DIC1)45ImportCollections6 dic = collections.defaultdict (list)#Specifies the value of the dictionary as a list7 dic["k1 "].append (" kkkkk ")  8 print (DIC)  9 10 # Execution Result: 11 defaultdict (<class  "list", {k1": [ " kkkkk "})         

1#Has the following value collection,do not use the default dictionary code as follows2#[11,22,33,44,55,66,77,88,99,90]3#Save all values greater than 66 in the first key of the dictionary,4#Save a value of less than or equal to 66 in the value (list) of the second key.5#That is: {"K1": Greater Than, "K2": less than or equal to 66}67 Li = [11,22,33,44,55,66,77,88,99,90]8 dic ={}910For IInchLi11If i>66:12If"K1"InchDic.keys ():dic["K1"].append (i)14Else:dic["K1"] =[I,]16Else:17If"K2"InchDic.keys ():dic["K2 "].append (i) 19 else:20 dic[" k2 "] = [I,]21 print (DIC) 22 23 # execution result: Span style= "COLOR: #008080" >24 { "k2 ' k1": [All-in-a-.]}             
1#refine your code with the default dictionary2From collectionsImportDefaultdict #这样写, you don't have to write collections.defaultdict down here.3 values = [11, 22, 33,44,55,66,77,88,99,90]4 My_dict =Defaultdict (list)56For valueInchValues7If value>66:8 my_dict[‘K1‘].append (value)9Else:10 my_dict[ "k2 ' ].append (value) 11 print (my_dict) 12 13 # execution result: 14 defaultdict (<class " list", {k2 ": [11, 22, 33, 44, 55, 66],  ' k1 ": [77, 88, 99, 90]})  

Introduction to Python defaultdict types in the collections module

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.