The "python-dictionary" determines whether a key exists in the Python dictionary

Source: Internet
Author: User

There are generally two common practices:

The first approach: using a self-implemented function:

There is a Has_key () method in the property method of the Python dictionary:

[Python]View PlainCopy
    1. #生成一个字典
    2. D = {' name ': Tom, ' age ':ten, ' Tel ':
    3. #打印返回值
    4. Print D.has_key (' name ')
    5. #结果返回True


The second method: Use the In method:

[Python]View PlainCopy
    1. #生成一个字典
    2. D = {' name ': Tom, ' age ':ten, ' Tel ':
    3. #打印返回值, where D.keys () is a list of all keys in the dictionary
    4. print ' name ' in D.keys ()
    5. Print ' name ' in D
    6. #两个的结果都是返回True


In addition to using in, you can determine that the key does not exist and use in is faster than Has_key.

The "python-dictionary" determines whether a key exists in the Python dictionary

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.