Skip to main content
Practice

Utilizing Values Within a Dictionary

To retrieve the value of a specific key in a dictionary, input the key within square brackets [].

For example, the line name = person["name"] returns the value corresponding to the name key, "John".

Accessing Dictionary Elements
person = {
"name": "John",
"age": 30,
"job": "Developer"
}

# Retrieve the value corresponding to the "name" key from the person dictionary
name = person["name"]

# Output: Name: John
print(f"Name: {name}")

What happens if you access a non-existent key?

When you try to access a non-existent key in a dictionary, a KeyError is raised.

Accessing a Non-existent Key
person = {
"name": "John",
"age": 30,
"job": "Developer"
}

# The key 'address' does not exist
address = person["address"]
# KeyError is raised

To check if a specific key exists in a dictionary, you can use the in operator.

Checking Key Existence Using the in Operator
# Check if the 'address' key exists
if "address" in person:
address = person["address"]
else:
address = "Not Registered"

Safely Accessing with the get() Method

The get() method allows you to access a key and returns a default value if the key doesn't exist, helping you manage data without errors.

Safe Access Example Using the get() Method
person = {
"name": "John",
"age": 30,
"job": "Developer"
}

# Access the 'address' key, return "Not Registered" if the key is absent
address = person.get("address", "Not Registered")

# Address: Not Registered
print(f"Address: {address}")

If no default value is provided, the get() method returns None.


Accessing All Keys and Values of a Dictionary

To access all keys and values of a dictionary, use the keys(), values(), and items() methods.

In programming, a method refers to a function that belongs to an object. keys(), values(), items() are methods of a dictionary object that return the keys, values, and key-value pairs of the dictionary, respectively.

Accessing All Keys and Values of a Dictionary
keys = person.keys()
# dict_keys(['name', 'age', 'job'])
print(keys)

values = person.values()
# dict_values(['John', 30, 'Developer'])
print(values)

items = person.items()
# dict_items([('name', 'John'), ('age', 30), ('job', 'Developer')])
print(items)

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.