6️⃣

9.6 Check Key/Value Membership in a Dictionary

Check Key/Value Membership in a Dictionary

To check if a key or value is in a dictionary, use the in keyword.

# Check Key/Value Membership in a Dictionary

contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"}

if "Daisy Johnson" in contacts:
    print("Daisy Johnson is a key in contacts")
else:
    print("Daisy Johnson is not a key in contacts")

if "1234 Main St" in contacts.values():
    print("1234 Main St is a value in contacts")
else:
    print("1234 Main St is not a value in contacts")

View code on GitHub.

Output of the above code:

Daisy Johnson is a key in contacts
1234 Main St is not a value in contacts

Previous Section

Next Section

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.