The basic way to access a dictionary value

To get a value from a Python dictionary, put the key inside square brackets right after the dictionary name. If your dictionary is called student and has a key called name, you write student["name"] to retrieve that value. The key must be exactly as it appears in the dictionary — Python treats "Name" and "name" as different keys.

This works when you know the key exists. If the key is not there, Python stops and shows an error message. For example, if you try to access student["age"] but the dictionary has no "age" key, you will get a KeyError. This error tells you the key was not found, and your program halts at that line.

Key Takeaways

  • Use square brackets with the key name to access a dictionary value: dictionary[key] returns the value paired with that key.
  • The get() method lets you access a value safely and provide a default if the key does not exist, preventing errors.
  • Check whether a key exists before accessing it by using the in operator: if key in dictionary.
  • Square brackets throw an error if the key is missing, while get() returns None or a default value you specify instead.
  • Chain square brackets together to access nested dictionaries, or use get() at each level to avoid errors when keys are missing.

Using the get() method for safer access

The get() method is safer than square brackets because it does not crash if the key is missing. Instead, it returns None by default. You write it as student.get("name") to retrieve the value, or student.get("name", "Unknown") to return the word "Unknown" if the key does not exist.

This approach is useful when you are not sure whether a key is in the dictionary. Your program keeps running instead of stopping with an error. You can then check what get() returned and decide what to do next. The second argument to get() can be any value — a string, a number, an empty list, or even another dictionary.

Checking if a key exists before accessing it

You can test whether a key is in a dictionary using the in operator before you try to access it. Write if "name" in student: followed by the code you want to run only if that key exists. This prevents errors and lets you handle missing keys the way you want.

This method is clearer than using get() when you need to do different things depending on whether the key is there. For example, you might print one message if the key exists and a different message if it does not. The in operator returns True or False, so you can use it in any conditional statement.

Accessing nested dictionary values

When a dictionary contains another dictionary inside it, you chain the square brackets together. If student contains a dictionary called address, and that address dictionary has a key called city, you write student["address"]["city"] to get the city value. Python evaluates this from left to right, first finding the address dictionary, then finding the city key inside it.

Be careful with nested dictionaries: if any key in the chain is missing, you will get a KeyError. Use get() at each level to stay safe, like student.get("address", {}).get("city", "Unknown"). This returns "Unknown" if either the address key or the city key is missing. The empty dictionary {} as the default for the first get() ensures the second get() has something to work with.

Looping through dictionary keys and values

When you need to access many values at once, loop through the dictionary instead of typing each key separately. Use for key in dictionary: to loop through keys, or for key, value in dictionary.items(): to loop through both keys and their values at the same time.

The items() method is especially useful because it gives you both pieces of information in each loop. You can then print them, store them, or check them without having to look up each value separately. You can also use dictionary.keys() to loop through only the keys, or dictionary.values() to loop through only the values.

Accessing values from a list of dictionaries

When you have a list that contains multiple dictionaries, access each dictionary by its position in the list first, then access the value inside that dictionary. If students is a list of student dictionaries, students[0]["name"] gets the name from the first student, and students[1]["name"] gets the name from the second student. Remember that Python counts positions starting from zero.

You can combine this with a loop to access the same key from every dictionary in the list. Write for student in students: followed by print(student["name"]) to print the name of each student without typing the index number each time. This is cleaner and more flexible than accessing each position manually.

Frequently Asked Questions

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

Square brackets throw an error if the key does not exist, while get() returns None or a default value instead. Use square brackets when you know the key is there, and use get() when you are not sure.

Can I use a variable as a dictionary key?

Yes. If you have a variable called key_name that contains the string "name", you can write dictionary[key_name] and it will work the same way as dictionary["name"]. The variable is evaluated first, then used as the key.

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

Using square brackets raises a KeyError and stops your program. Using get() returns None by default, or whatever default value you provided as the second argument. Your program keeps running either way.

How do I access a dictionary value if the key has spaces in it?

Keys with spaces work the same way as any other key. Write dictionary["key with spaces"] using square brackets and quotes around the entire key, including the spaces.

Can I use numbers as dictionary keys?

Yes. You can use integers, floats, or strings as keys. If you use a number as a key, access it without quotes: dictionary[1] looks for the key 1, while dictionary["1"] looks for the key "1" — these are different keys.