The basic way to pull a value from a dictionary

A dictionary in Python is a container that stores pairs of things: a key (the label) and a value (what you want to find). To get the value out, you use square brackets with the key inside, like this:

my_dict = {"name": "Alice", "age": 30} print(my_dict["name"]) This prints: Alice

The key must match exactly — uppercase, lowercase, spelling, everything. If you ask for a key that does not exist, Python stops and throws an error called a KeyError. This is the most direct method and works when you are certain the key is there.

Key Takeaways

  • Square brackets with the key name inside — my_dict["key"] — is the standard way to retrieve a value from a dictionary.
  • If the key does not exist, Python raises a KeyError and your program stops unless you handle it.
  • The .get() method lets you retrieve a value safely and provide a fallback if the key is missing.
  • You can loop through all keys and values at once using .items(), or just keys with .keys(), or just values with .values().
  • Nested dictionaries (dictionaries inside dictionaries) require chaining brackets: my_dict["outer"]["inner"].

Using .get() to avoid errors when a key might not exist

The safer way to retrieve a value is the .get() method. Instead of crashing if the key is missing, it returns None or a default value you specify:

my_dict = {"name": "Alice", "age": 30} print(my_dict.get("name")) returns Alice print(my_dict.get("email")) returns None print(my_dict.get("email", "not found")) returns "not found"

Use .get() when you are not sure the key exists or when you want your program to keep running even if it does not. Use square brackets when you know the key must be there and you want to catch mistakes early. The .get() method is especially useful in real programs where data comes from outside sources like user input or web requests, where keys might be missing unpredictably.

Looping through all keys and values

Sometimes you need to look at every key-value pair, not just one. The .items() method gives you both at once:

my_dict = {"name": "Alice", "age": 30, "city": "Boston"} for key, value in my_dict.items():   print(f"{key}: {value}") This prints: name: Alice age: 30 city: Boston

If you only need the keys, use .keys(). If you only need the values, use .values(). The order of items in a dictionary is the order they were added (in Python 3.7 and later). This matters when you are building reports or processing data in a specific sequence.

Accessing values inside nested dictionaries

A dictionary can contain another dictionary as a value. To reach the inner value, chain the brackets:

person = {   "name": "Alice",   "address": {"street": "123 Main St", "city": "Boston"} } print(person["address"]["city"]) returns Boston

If you are not sure the inner key exists, combine chaining with .get():

print(person.get("address", {}).get("city")) This returns Boston if both keys exist, or None if either one is missing. The empty dictionary {} in the first .get() acts as a fallback, so the second .get() always has something to work with.

Checking if a key exists before retrieving it

You can test whether a key is in the dictionary using the in keyword:

my_dict = {"name": "Alice", "age": 30} if "name" in my_dict:   print(my_dict["name"]) else:   print("Key not found")

This approach is useful when you want to do different things depending on whether the key exists. It is clearer than using .get() when your code needs to branch into separate paths. You can also use this pattern to decide whether to retrieve a value with square brackets (which you know is safe) or handle a missing key with different logic.

Retrieving values from a list of dictionaries

Often you have a list where each item is a dictionary. Loop through the list and pull the value you need from each one:

people = [   {"name": "Alice", "age": 30},   {"name": "Bob", "age": 25} ] for person in people:   print(person["name"]) This prints: Alice Bob

If some dictionaries in the list might be missing a key, use .get() inside the loop to avoid stopping the whole program on one missing value. This pattern appears constantly in real programs — when you fetch data from a database or API, you often get back a list of dictionaries, and not every record has every field filled in.

Frequently Asked Questions

What is the difference between square brackets and .get()?

Square brackets raise a KeyError if the key does not exist and stop your program. The .get() method returns None (or a default value you set) and lets your program keep running. Use square brackets when the key must exist; use .get() when it might not.

Can I use a number or other type as a dictionary key?

Yes. Keys can be strings, numbers, tuples, or any immutable type. You retrieve them the same way: my_dict[1] or my_dict[(1, 2)]. Lists and dictionaries cannot be keys because they can change.

What happens if I try to access a key that does not exist with square brackets?

Python raises a KeyError and stops running your code. The error message tells you which key was not found. This is why .get() is safer when you are not certain the key exists.

How do I get all the values from a dictionary at once?

Use the .values() method to get a list-like object of all values: all_values = my_dict.values(). You can loop through it or convert it to a list with list(my_dict.values()).

Can I change a value in a dictionary after I retrieve it?

Yes. Assign a new value to the key: my_dict["name"] = "Bob". This overwrites the old value. You can also add new keys the same way: my_dict["email"] = "bob@example.com".