Usage of defaultdict in python: pythondefaultdict

Source: Internet
Author: User

Usage of defaultdict in python: pythondefaultdict

First recognized by defaultdict

Previously, when using dictionaries, they were relatively casual, but simply using dict.
However, if a KeyError occurs when a non-existent key is used, defaultdict should be launched.

How to Use defaultdict

Yes.

from collections import defaultdictd1 = defaultdict(int)

Or

import collectionsd1 = collections.defaultdict(int)

Difference between ultdict and dict instantiation dictionary types

If defaultdict is used for any undefined key, a default value based on the method_factory parameter is returned by default. In the same case, dict () returns KeyError.
Compare the following code:

d1 = dict()d2 = defaultdict(list)print(d1['a'])print(d2['a'])

Defaultdict Construction

The official python document defines defaultdict as follows:

class collections.defaultdict([default_factory[, ...]])

The official python document explains defaultdict as follows:

defaultdicdict subclass that calls a factory function to supply missing values

Default_factory receives a factory function as a parameter, such as int str list set.
Defaultdict adds a missing (key) Method Based on dict. When a non-stored key is called, defaultdict calls _ missing __and returns a default value based on the default_factory parameter, therefore, Keyerror is not returned.

Example

Example 1

s = 'mississippi'd = defaultdict(int)for k in s:  d[k] += 1print(d)

Example 2

s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]d = defaultdict(set)for k, v in s:  d[k].add(v)print(d)

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.