← Back to Chapters

Python Access Dictionary Items

?️ Python Access Dictionary Items

⚡ Quick Overview

Dictionaries in Python store data as key–value pairs. To work with them effectively, you must know how to access values safely and efficiently.

  • Use square brackets [] to access a value directly by its key.
  • Use get() to safely access a value and avoid KeyError.
  • Use keys(), values(), and items() to access dictionary views.
  • Loop through dictionaries using keys, values or key–value pairs.

? Key Concepts

  • Key: The identifier used to access a value (e.g., "name").
  • Value: The data associated with a key (e.g., "Alice").
  • Direct access: dict[key] returns the value or raises KeyError if missing.
  • Safe access: dict.get(key, default) returns the value or a default if the key is missing.
  • Views: keys(), values(), and items() return dynamic views of the dictionary.
  • Iteration: You can loop over keys, values, or key–value pairs using for loops.

? Syntax and Theory

A Python dictionary is defined using curly braces {} with key–value pairs:

dictionary_name = {"key1": value1, "key2": value2}

  • Access by key using []: dictionary_name["key1"]
  • Safe access using get(): dictionary_name.get("key1", default_value)
  • All keys: dictionary_name.keys()
  • All values: dictionary_name.values()
  • All items (key, value): dictionary_name.items()

? Code Examples

? Accessing Values by Key

You can access dictionary values using the key inside square brackets []. If the key does not exist, Python raises a KeyError.

? View Code Example
person = {"name": "Alice", "age": 25, "city": "New York"}

print(person["name"])  # Alice
print(person["age"])   # 25

?️ Using get() Method

The get() method allows you to access a value safely. If the key does not exist, it returns None or a default value if provided.

? View Code Example
print(person.get("name"))                 # Alice
print(person.get("email"))                # None
print(person.get("email", "Not Found"))   # Not Found

? Accessing Keys, Values, and Items

Dictionaries provide methods to access all keys, all values, or key–value pairs as dynamic views.

? View Code Example
print(person.keys())    # dict_keys(['name', 'age', 'city'])
print(person.values())  # dict_values(['Alice', 25, 'New York'])
print(person.items())   # dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')])

? Iterating Through a Dictionary

You can loop through the dictionary using keys or items to access both keys and values.

? View Code Example
# Loop through keys
for key in person:
    print(key, person[key])

# Loop through items
for key, value in person.items():
    print(key, "->", value)

? Live Output and Explanation

? What the Code Prints

For the dictionary:

person = {"name": "Alice", "age": 25, "city": "New York"}

  • person["name"] prints Alice.
  • person["age"] prints 25.
  • person.get("email") returns None because the key "email" does not exist.
  • person.get("email", "Not Found") returns the default string "Not Found".
  • person.keys() returns a view object of all keys: dict_keys(['name', 'age', 'city']).
  • person.values() returns all values: dict_values(['Alice', 25, 'New York']).
  • person.items() returns key–value pairs: dict_items([('name', 'Alice'), ('age', 25), ('city', 'New York')]).
  • Looping with for key, value in person.items() prints lines like name -> Alice, age -> 25, etc.

? Use Cases

  • Storing user profiles (name, age, email, city, etc.).
  • Configuration settings where each option has a name and a value.
  • Counting occurrences of items using keys as categories.
  • Quick lookups where you need fast access by a unique key.

? Tips and Best Practices

  • Use get() to avoid KeyError for missing keys.
  • items() is very useful for looping through both keys and values simultaneously.
  • keys() and values() provide dynamic views, which update automatically if the dictionary changes.
  • Use meaningful key names so your code is easier to read and understand.
  • When unsure if a key exists, prefer get() or in operator (e.g., "email" in person).

? Try It Yourself

  • Create your own person dictionary and access a value using [] and get() for the same key.
  • Try accessing a missing key using [] and see the KeyError. Then fix it using get() with a default value.
  • Loop through keys and print their values using both for key in dict and for key in dict.keys().
  • Loop through items() and format the output as key -> value.
  • Add a new key–value pair to the dictionary and verify that keys(), values(), and items() reflect the change.