A brief introduction to the usage of defaultdict types in Python's collections module _python

Source: Internet
Author: User
Tags in python

Defaultdict is primarily used for situations where value initialization is required. For a dictionary, the 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 empty before it is used, and in some cases you need to initialize value to a special value, such as 0 or '.

From collections import defaultdict

person_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 access to a nonexistent key, the value automatically set to X (). For example, the first time someone who accesses a certain age D[person.age] becomes a list (), which is [].

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

D = defaultdict (lambda:0)
d["Hello"] + = 1     # 1
d["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, and a default value if the value does not exist. The Defaultdict initialization container will allow the caller to specify the default value ahead of time.

Import Collections
def default_factory (): Return
  ' default value '
d = collections.defaultdict (default_ Factory, foo = ' bar ')
print ' d: ', D
print ' foo => ', d[' foo ']
print ' var => ', d[' bar '

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

D:defaultdict (<function default_factory at 0x0201fab0>, {' foo ': ' Bar '})
foo => bar
var => default V Alue

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.