Meta-Group to Dictionary

Source: Internet
Author: User
Tuples: 1. Use brackets (()) to wrap, can not be changed (although their content can), tuples can be viewed as a read-only list

A. Dict.fromkeys (S)

S is a list or tuple ...

The key,value of the elements in S as the dictionary defaults to none, or you can specify an initial value, as shown in the following code example:

Mydict = Dict.fromkeys (' Hello ', True) for K in Mydict.keys ():    print (k, mydict[k])

The output is as follows:

H True

E True

L True

o True

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

Default_factory the value type of the specified dictionary

>>> s = [(' Yellow ', 1), (' Blue ', 2), (' Yellow ', 3), (' Blue ', 4), (' Red ', 1)]>>> d = defaultdict (list) ;>> for K, V in S: ...     D[k].append (v) ...>>> d.items ('   blue ', [2, 4]), (' Red ', [1]), (' Yellow ', [1, 3])]

The above code efficiency is higher than the following equivalent code:

>>> d = {}>>> for K, V in S: ...     D.setdefault (k, []). Append (v) ...>>> D.items ()

[(' Blue ', [2, 4]), (' Red ', [1]), (' Yellow ', [1, 3])]

If an int is passed to default_dict, it can be used to count:

>>> s = ' Mississippi ' >>> d = defaultdict (int) >>> for k in s: ...     D[k] + = 1...>>> D.items ()

[(' I ', 4), (' P ', 2), (' s ', 4), (' m ', 1)]

  • 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.