Python solves a list problem with values in a dictionary _python

Source: Internet
Author: User

Question: Find some English words in which of the small sentences appear, of course, is implemented in Python, of course, with the dictionary, but how to make a key corresponding to a type of the list of value, directly with the list of append () is not possible, such as dic[key].append (value) , because the interpreter does not know the type of dic[key], when in a hurry, with a compromise scheme, is to use value into a str, and finally use Str.split () as a conversion, to generate a list.

Looking at the Python cookbook, there is just a recipe about how to deal with such a problem, well, find out the answer!

(1) A duplicate entry is allowed in value.

Copy Code code as follows:

DIC = {}
Dic.setdefault (key,[]). Append (value)
#如:
D1.setdefault (' Bob_hu ', []). Append (1)
D1.setdefault (' Bob_hu ', []). Append (2)
Print d1[' Bob_hu '] # [1,2]

(2) There are no duplicates in value.

Copy Code code as follows:

DIC = {}
Dic.setdefault (key,{}) [Value] = 1
#如:
D1.setdefault (' Bob ', {}) [' f '] = 1
D1.setdefault (' Bob ', {}) [' h '] = 1
D1.setdefault (' Bob ', {}) [' f '] = 1
Print d1[' Bob '] #{' h ': 1, ' F ': 1}

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.