🎓 A1Learner
🔍

Python Access Dictionary Items

Dictionary access reads a value from a dictionary by its key.

Read with square brackets

Put the key inside square brackets.

capitals = {"France": "Paris", "Japan": "Tokyo"}
print(capitals["France"])

A missing key

Square brackets fail when the key is not there. This error is called KeyError.

capitals = {"France": "Paris"}
print(capitals["Spain"])

Read safely with get()

get() returns None when the key is missing. None means no value yet.

capitals = {"France": "Paris"}
print(capitals.get("France"))
print(capitals.get("Spain"))

Give get() a default

A default is the value get() returns instead. It is used only when the key is missing.

capitals = {"France": "Paris"}
print(capitals.get("Spain", "Not known"))

See keys, values, and pairs

list() turns each view into a list. Then you can print the whole view.

capitals = {"France": "Paris", "Japan": "Tokyo"}
print(list(capitals.keys()))
print(list(capitals.values()))
print(list(capitals.items()))

Test for a key

in asks if a key is present. The answer is True or False.

capitals = {"France": "Paris", "Japan": "Tokyo"}
print("France" in capitals)
print("Paris" in capitals)
print("Spain" not in capitals)

Example

capitals = {"France": "Paris", "Japan": "Tokyo", "Brazil": "Brasilia"}
print("France:", capitals.get("France", "Not known"))
print("Japan:", capitals.get("Japan", "Not known"))
print("Germany:", capitals.get("Germany", "Not known"))

Key points

  • Use square brackets with a key to read its value
  • View: a live look at a dictionary's keys, values, or pairs
  • Use keys() to get a view of all the keys
  • Use values() to get a view of all the values
  • Use items() to get a view of all the pairs
  • Membership test: a check with in or not in
  • A value stored in the dictionary does not count as a match.

In this example, capitals holds three country and capital pairs. The first get() finds France and returns Paris. The second get() finds Japan and returns Tokyo. Germany is not a key in the dictionary. So get() returns the default, Not known, and no error stops the program.

Note

The in test checks keys only.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which code prints Not known instead of raising KeyError when Spain is missing?