Python solves the Value List problem in the dictionary.

Source: Internet
Author: User

Problem: Find out the small sentences in which some English words appear. Of course, it is implemented in Python. Of course, it is a dictionary. But how can we make a key correspond to a value of the list type, you cannot directly use the list append (), for example, DIC [Key]. append (value), because the interpreter does not know the DIC [Key] type. In a short time, it used a compromise solution, that is, to connect the value into a STR, and finally use Str. split () is converted to generate a list.

After reading the python cookbook, there is just a recipe on it to talk about how to deal with such a problem. Well, let's reveal the answer!

(1) repeated items are allowed in value.

CopyCodeThe Code is as follows: DIC = {}
Dic. setdefault (Key, []). append (value)
# Example:
D1.setdefault ('Bob _ hu', []). append (1)
D1.setdefault ('Bob _ hu', []). append (2)
Print D1 ['Bob _ hu'] # [1, 2]

(2) No repeated items in value.

Copy codeThe Code is as follows: DIC = {}
Dic. setdefault (Key, {}) [value] = 1
# Example:
D1.setdefault ('bob', {}) ['F'] = 1
D1.setdefault ('bob', {}) ['H'] = 1
D1.setdefault ('bob', {}) ['F'] = 1
Print D1 ['bob'] # {'H': 1, 'F': 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.