About Python's defaultdict

Source: Internet
Author: User

Original address: http://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html

The author first looked at Defaultdict's help explanation, the author read the explanation and translated the English translation out, found still can not understand.

The latter is understood directly by looking at the example. Find the author is very humorous.

Posted below,defaultdict(), SetDefault and normal {} code

Compared to defaultdict and setdefault , the efficiency ofdefaultdict is higher.

The normal {} can only be assigned (because you will not find the key if you append the operation directly)

ImportCollectionss= [('Yellow', 1), ('Blue', 2), ('Yellow', 3), ('Blue', 4), ('Red', 1)]#defaultdictD =collections.defaultdict (list) forKvinchS:d[k].append (v) # D results for {' Blue ': [2, 4], ' Red ': [1], ' yellow ': [1, 3]
#Use dict and SetDefaultg = {} forKvinchS:g.setdefault (k, []). Append (v) # G The result is {' Blue ': [2, 4], ' Red ': [1], ' yellow ': [1, 3]}#Use dictE = {} forKvinchS:e[k]=V
# e result {' Blue ': 4, ' Red ': 1, ' Yellow ': 3}

About Python's 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.