Skip to content

Access the dictionary

You can access dictionary items by their keys. If you try to access a key that does not exist, you will get a KeyError exception.

You can access dictionary items by their keys. The following example accesses the key name of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1["name"])

Output:

command
C:\Users\username>python dict.py
John

In this example, we access the key name of the dictionary dict1. We then print the value of the key to the console. The output shows that the value of the key is John.

You can access dictionary items by their keys using the get() method. If you try to access a key that does not exist, you will get None. The following example accesses the key name of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("name"))

Output:

command
C:\Users\username>python dict.py
John

In this example, we access the key name of the dictionary dict1. We then print the value of the key to the console. The output shows that the value of the key is John.

Accessing a Key that Does Not Exist using the get() Method

Section titled “Accessing a Key that Does Not Exist using the get() Method”

You can access dictionary items by their keys using the get() method. If you try to access a key that does not exist, you will get None. The following example accesses a key that does not exist:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(dict1.get("address"))

Output:

command
C:\Users\username>python dict.py
None

In this example, we try to access the key address of the dictionary dict1. We then print the value of the key to the console. The output shows that we get None because the key does not exist.

The length of a dictionary is the number of key-value pairs it contains. You can use the len() function to get the length of a dictionary. The following example gets the length of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
print(len(dict1))

Output:

command
C:\Users\username>python dict.py
3

In this example, we get the length of the dictionary dict1. We then print the length of the dictionary to the console. The output shows that the length of the dictionary is 3.

You can iterate over a dictionary using a for loop. When you iterate over a dictionary, you get the keys of the dictionary. The following example iterates over the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for key in dict1:
    print(key + " => " + str(dict1[key]))

Output:

command
C:\Users\username>python dict.py
name => John
age => 30
city => New York

In this example, we iterate over the dictionary dict1. We then print the keys and values of the dictionary to the console. The output shows that we get the keys of the dictionary.

Accessing the Dictionary Items using the keys() Method

Section titled “Accessing the Dictionary Items using the keys() Method”

You can access the dictionary items using the keys() method. The following example accesses the dictionary items using the keys() method:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for key in dict1.keys():
    print(key + " => " + str(dict1[key]))

Output:

command
C:\Users\username>python dict.py
name => John
age => 30
city => New York

In this example, we iterate over the dictionary dict1. We then print the keys and values of the dictionary to the console. The output shows that we get the keys of the dictionary.

Accessing the Dictionary Items using the values() Method

Section titled “Accessing the Dictionary Items using the values() Method”

You can access the dictionary items using the values() method. The following example accesses the dictionary items using the values() method:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for value in dict1.values():
    print(value)

Output:

command
C:\Users\username>python dict.py
John
30
New York

In this example, we iterate over the dictionary dict1. We then print the values of the dictionary to the console. The output shows that we get the values of the dictionary.

Accessing the Dictionary Items using the items() Method

Section titled “Accessing the Dictionary Items using the items() Method”

You can access the dictionary items using the items() method. The following example accesses the dictionary items using the items() method:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
for key, value in dict1.items():
    print(key + " => " + str(value))

Output:

command
C:\Users\username>python dict.py
name => John
age => 30
city => New York

In this example, we iterate over the dictionary dict1. We then print the keys and values of the dictionary to the console. The output shows that we get the keys and values of the dictionary.

You can check if a key exists in a dictionary using the in operator. The following example checks if the key name exists in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if "name" in dict1:
    print("The key 'name' exists in the dictionary")

Output:

command
C:\Users\username>python dict.py
The key 'name' exists in the dictionary

In this example, we check if the key name exists in the dictionary dict1. We then print a message to the console. The output shows that the key exists in the dictionary.

You can check if a key does not exist in a dictionary using the not in operator. The following example checks if the key address does not exist in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if "address" not in dict1:
    print("The key 'address' does not exist in the dictionary")

Output:

command
C:\Users\username>python dict.py
The key 'address' does not exist in the dictionary

In this example, we check if the key address does not exist in the dictionary dict1. We then print a message to the console. The output shows that the key does not exist in the dictionary.

You can check if a value exists in a dictionary using the in operator. The following example checks if the value John exists in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if "John" in dict1.values():
    print("The value 'John' exists in the dictionary")

Output:

command
C:\Users\username>python dict.py
The value 'John' exists in the dictionary

In this example, we check if the value John exists in the dictionary dict1. We then print a message to the console. The output shows that the value exists in the dictionary.

You can check if a value does not exist in a dictionary using the not in operator. The following example checks if the value Jane does not exist in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if "Jane" not in dict1.values():
    print("The value 'Jane' does not exist in the dictionary")

Output:

command
C:\Users\username>python dict.py
The value 'Jane' does not exist in the dictionary

In this example, we check if the value Jane does not exist in the dictionary dict1. We then print a message to the console. The output shows that the value does not exist in the dictionary.

Checking if a Key Exists using the get() Method

Section titled “Checking if a Key Exists using the get() Method”

You can check if a key exists in a dictionary using the get() method. The following example checks if the key name exists in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if dict1.get("name"):
    print("The key 'name' exists in the dictionary")

Output:

command
C:\Users\username>python dict.py
The key 'name' exists in the dictionary

In this example, we check if the key name exists in the dictionary dict1. We then print a message to the console. The output shows that the key exists in the dictionary.

Checking if a Key Does Not Exist using the get() Method

Section titled “Checking if a Key Does Not Exist using the get() Method”

You can check if a key does not exist in a dictionary using the get() method. The following example checks if the key address does not exist in the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
if not dict1.get("address"):
    print("The key 'address' does not exist in the dictionary")

Output:

command
C:\Users\username>python dict.py
The key 'address' does not exist in the dictionary

In this example, we check if the key address does not exist in the dictionary dict1. We then print a message to the console. The output shows that the key does not exist in the dictionary.

You can change the value of a dictionary item by using its key.

You can change the value of a dictionary item by using its key. The following example changes the value of the key name of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
dict1["name"] = "Jane"
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'Jane', 'age': 30, 'city': 'New York'}

In this example, we change the value of the key name of the dictionary dict1. We then print the dictionary to the console. The output shows that the value of the key is changed to Jane.

You can change the value of a dictionary item by using its key. The following example changes the value of the key address of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
dict1["address"] = "London"
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'address': 'London'}

In this example, we change the value of the key address of the dictionary dict1. We then print the dictionary to the console. The output shows that the value of the key is changed to London.

You can change the value of a dictionary item by using its key. The following example changes the value of the key name of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
dict1.update({"name": "Jane"})
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'Jane', 'age': 30, 'city': 'New York'}

In this example, we change the value of the key name of the dictionary dict1. We then print the dictionary to the console. The output shows that the value of the key is changed to Jane.

Changing a Key that Does Not Exist using the update() Method

Section titled “Changing a Key that Does Not Exist using the update() Method”

You can change the value of a dictionary item by using its key. The following example changes the value of the key address of the dictionary dict1:

dict.py
dict1 = {"name": "John", "age": 30, "city": "New York"}
dict1.update({"address": "London"})
print(dict1)

Output:

command
C:\Users\username>python dict.py
{'name': 'John', 'age': 30, 'city': 'New York', 'address': 'London'}

In this example, we change the value of the key address of the dictionary dict1. We then print the dictionary to the console. The output shows that the value of the key is changed to London.

In this tutorial, you have learned how to access the dictionary in Python. You also known as how to access the dictionary in Python using the key. You will also learn how to access the dictionary in Python using the get() method. You change the value of the dictionary in Python. For more tutorials, visit our Python Central Hub.


diagram the three views, and which support set operations mermaid
keys, values and items are live windows on the dictionary rather than snapshots. Two of them behave like sets, because keys are unique and hashable -- which lets you intersect two dictionaries' keys directly. values cannot, because values may repeat and need not be hashable at all.
sketch Reading a key: four spellings, measured p5.js
Square brackets are the fastest because they are an operator rather than a method call, and they raise on a miss. get costs a method call and returns a default instead. The difference is around thirty nanoseconds, so choose by what should happen when the key is absent -- not by speed.
pch.quizTag pch.quizDefaultTitle
  1. `d.keys() & {'a', 'z'}` works, but `d.values() & {1}` raises. Why?

    pch.quizShowAnswer

    B — Keys are unique and hashable, so the view is set-like; values may repeat and need not be hashable — Verified: `TypeError: unsupported operand type(s) for &: 'dict_values'`. `items()` is set-like too, as long as the values happen to be hashable.

  2. You take `ks = d.keys()` and then add a key. What does `list(ks)` show?

    pch.quizShowAnswer

    B — The new key too — views are live — Views are windows, not snapshots. The related rule: mutating a dict while iterating it raises `RuntimeError: dictionary changed size during iteration`.

  3. `d['a']` measured 112.6 ns and `d.get('a')` 145.1 ns. What should decide which you use?

    pch.quizShowAnswer

    B — What should happen when the key is missing — Thirty nanoseconds is a method call, not an algorithmic difference. `d[k]` raises — right when absence is a bug. `get` returns a default — right when absence is expected.

  4. What is the risk of reaching for `.get()` everywhere?

    pch.quizShowAnswer

    B — A genuinely missing key becomes a `None` that travels until it breaks something unrelated — `KeyError` names the missing key at the line that wanted it. A silent `None` surfaces later as a `TypeError` somewhere with no obvious connection to the real mistake.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading