[How do keys in the py3]--dictionary map multiple values?] How are dictionaries sorted?

Source: Internet
Author: User

Defaultdict Default Dictionary
    • The Defaultdict (default dictionary) in the collections module, which can be used to construct a dictionary such as "one key map multiple values"
    • If you want to keep the elements in the order of insertion, you should use list, if you want to remove the duplicate elements, use set
Import Import defaultdict
D=defaultdict (list) /

D= { ' a ' : [1< Span class= "P", 23,  ' B ' Span class= "P" >: [45 }e = { ' a ' : {123 },  ' B ' : {4 Span class= "Mi" >5}}          
    • Note that the defaultdict will automatically create a mapped entity for the key that will be accessed, even if there is no such key in the current dictionary
 fromCollectionsImportdefaultdict
D=defaultdict (list) d[1].append ('a') d[1].append ('b') d[2].append ('a')Print(D[0]) []//even though we did not assign a value to d[0, we still have a pit for this position.Print(d) defaultdict (<class 'List'{0: [], 1: ['a','b'], 2: ['a']}) Q=defaultdict (set) Q[0].add ('A0') Q[0].add ('B0') Q[0].add ('C0') q[1].add ('D1')Print(q) defaultdict (<class 'Set'{0: {'B0','C0','A0'}, 1: {'D1'}})
SetDefault
p={}p.setdefault ('1', []). Append ('a') P.setdefault ('1', []). Append ('b') P.setdefault ('2', []). Append ('C')Print(p[0]) keyerror:0#Contrary to the above, this does not occupy the pit.Print(p) {'2': ['C'],'1': ['a','b']}

Create a multi-valued mapping dictionary
D = {} for in pairs:    if not in D:        = []    = defaultdict (list) for in pairs:    d[key].append ( Value)

[How do keys in the py3]--dictionary map multiple values?] How are dictionaries sorted?

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.