Introduction to the defaultdict usage in the collections module of Python

Source: Internet
Author: User
Here we will introduce the defaultdict usage in the collections module of Python. The biggest difference from the built-in dictionary class lies in Initialization. let's take a look: defaultdict is mainly used to initialize the value. For the dictionary, the key must be hashable, immutable, and unique data, and the value can be any data type. If the value is a list, dict, or other data type, it must be initialized as null before use. in some cases, the value must be initialized as 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)

The usage of defaultdict is the same as that of dict. only a callable object x must be input during initialization. when a non-existent key is accessed, the value is automatically set to x (). For example, in the above example, when a person of a certain age d [person. age] is accessed for the first time, it becomes list (), that is, [].

You can also use custom callable objects, such:

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

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

The Standard Dictionary includes a method setdefault () to obtain a value. if the value does not exist, a default value is created. When ultdict initializes the container, the caller can 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']

This method can be used as long as all keys have the same default value.
The above result is:

d: defaultdict(
 
  , {'foo': 'bar'})foo => barvar => default value
 

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.