Lesson 50 +10 XP

Access Dictionary Items

Access Dictionary Items

Dictionaries give you several ways to pull values out.

Access by key

thisdict = {
    "brand": "Ford",
    "model": "Mustang",
    "year": 1964
}
print(thisdict["brand"])  # Ford

get()

print(thisdict.get("model"))  # Mustang

get with a default

If the key is missing, return your own fallback:

print(thisdict.get("color", "no color set"))  # no color set

keys() returns all keys

print(thisdict.keys())  # dict_keys(['brand', 'model', 'year'])

values() returns all values

print(thisdict.values())  # dict_values(['Ford', 'Mustang', 1964])

items() returns key-value pairs

print(thisdict.items())

Each item is a tuple (key, value).

Check if a key exists

if "model" in thisdict:
    print("Yes, 'model' is a key")

The in check looks at keys

Remember: in on a dictionary checks keys, not values.

TL;DR

  • dict[key] and dict.get(key) read values.
  • keys(), values(), items() give views of the data.
  • in checks whether a key exists.
  • get(key, default) returns a fallback.