Python collections.defaultdict

Source: Internet
Author: User

In fact, Defaultdict is a dictionary, but Python automatically assigns an initial value to its key. That is to say, you do not display the key for the dictionary to assign the initial value Python will not error, see the actual example.

For example, you want to calculate frequency

frequencies = {}for word in wordlist:    Frequencies[word] + = 1

Python throws a Keyerror exception because the dictionary index must be initialized before it can be resolved with the following method

For word in wordlist:    try:        Frequencies[word] + = 1    except Keyerror:        Frequencies[word] = 1
For word in wordlist:    if Word in frequencies:        Frequencies[word] + = 1    else:        Frequencies[word] = 1

Of course, collections.defaultdict can also easily solve this problem.

From collections Import defaultdictfrequencies = defaultdict (int) #传入int () function to initialize for word in wordlist:    frequencies[ Word] + = 1

Collections.defaultdict can accept a function as a parameter to initialize. What do you mean, look at the example above, we want Frequencies[word] to initialize to 0, then we can use an int () function as a parameter to defaultdict, we call int () without arguments, int () will return a 0 value

Reference: https://www.cnblogs.com/duyang/p/5065418.html

Python collections.defaultdict

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.