"Python Cookbook" "Data Structure and algorithm" 6. Map keys to multiple values in the dictionary

Source: Internet
Author: User

Problem: A dictionary that maps key (key) to multiple values (so-called one-key multi-valued dictionary [multidict])

Solution: If you want the key to be mapped to multiple values, you need to keep the multiple values in another container such as a list or collection;

>>> d={'a': [+],'b': [4,5]}>>>d{'b': [4, 5],'a': [1, 2, 3]}>>> e={'a': {1,2,3,3},'b': {4,5}}>>>e{'b': {4, 5},'a': {1, 2, 3}}>>> f={' a ': [1,2,3,3], ' B ': [4,5]}
>>> F
{' B ': [4, 5], ' a ': [1, 2, 3, 3]}
>>>

A more convenient way to create such a dictionary is to take advantage of the Defaultdict class in the collections module. One feature of Defaultdict is that it automatically initializes the first value to the dictionary so that only the elements can be added. For example:

 fromCollectionsImportDEFAULTDICTD=defaultdict (list)#creates a dictionary of multiple values for a key, and the value of key is the list typed['a'].append (1) d['a'].append (2) d['a'].append (2) d['b'].append (4) C=defaultdict (SET)#creates a dictionary of multiple values for a key, and the value of key is the set typec['a'].add (1) c['a'].add (2) c['a'].add (2) c['b'].add (4)Print('the value of key is a dictionary of the list type:', D)Print('the value of key is a dictionary of the set type:'C
>>> ================================ RESTART ================================>>>the value of key is a dictionary of list type: Defaultdict (<class 'List', {'b': [4],'a': [1, 2, 2]}) The value of key is a dictionary of the set type: Defaultdict (<class 'Set', {'b': {4},'a': {1, 2}})>>>

One thing to note about Defaultdict is that he automatically creates dictionary table entries for later access, even if they are not currently found in the dictionary.

If you want to cancel this function, you can call the SetDefault () method in a normal dictionary instead, for example:

# an ordinary dictionary d.setdefault ('a', []). Append (1) d.setdefault ('A  ', []). Append (2) d.setdefault ('a', []). Append (2) D.setdefault ('b', []). Append (4)
the value of >>> key is a dictionary of the list type: {'a''b': [4]}

Add:

It's easy to build a dictionary of one-click Multi-values, but if you try to initialize the first value yourself, this becomes messy, and if you use Defaultdic, the code will be much simpler:

 pairs={ " a  : [22,44],"   b  : [88 D  =defaultdict (list)  for  key,value in   Pairs.items (): D[key].append (value)   Print  (d) 
>>> defaultdict (<class'list'), {'a ' ' b ': [[[[]]}]

"Python Cookbook" "Data Structure and algorithm" 6. Map keys to multiple values in the dictionary

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.