Loading lessons...
Access Dictionary Items
Dictionaries give you several ways to pull values out.
Access by key
python
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
### Ford
get()
python
print(thisdict.get("model"))
### Mustang
get with a default
If the key is missing, return your own fallback:
python
print(thisdict.get("color", "no color set"))
### no color set
keys() returns all keys
python
print(thisdict.keys())
### dict_keys(['brand', 'model', 'year'])
values() returns all values
python
print(thisdict.values())
### dict_values(['Ford', 'Mustang', 1964])
items() returns key-value pairs
python
print(thisdict.items())
Each item is a tuple (key, value).
Check if a key exists
python
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]anddict.get(key)read values.keys(),values(),items()give views of the data.inchecks whether a key exists.get(key, default)returns a fallback.