Welcome to this tutorial on Creating and Accessing Dictionaries! This topic is crucial in mastering Python as dictionaries are one of the fundamental data structures used in programming. By the end of this tutorial, you'll be able to create your own dictionaries, access their elements, and understand how they can enhance your coding efficiency.
A dictionary in Python is a collection of key-value pairs. The keys must be unique, but values can be duplicated. Keys are typically strings or numbers, while values can be any data type. Dictionaries are created using curly braces {}
, and each item is represented as key: value
.
Example:
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
Here, 'name'
, 'age'
, and 'city'
are the keys, and 'John'
, 30
, and 'New York'
are their respective values.
Let's create a dictionary to store student information:
students = {
'Alice': {'age': 21, 'major': 'Computer Science'},
'Bob': {'age': 23, 'major': 'Mathematics'},
'Charlie': {'age': 20, 'major': 'Physics'}
}
Now, we can access the age of Alice like this:
print(students['Alice']['age']) # Output: 21
What causes it: Attempting to access a key that does not exist in the dictionary.
print(my_dict['unknown_key'])
Error message:
Traceback (most recent call last):
File "example.py", line 5, in <module>
print(my_dict['unknown_key'])
KeyError: 'unknown_key'
Solution: Use get()
method to avoid KeyErrors and specify a default value if the key is not found.
print(my_dict.get('unknown_key', "No such key exists"))
Why it happens: You're trying to access a key that doesn't exist in the dictionary.
How to prevent it: Always check if a key exists before attempting to access its value or use the get()
method with a default value.
What causes it: Trying to assign a non-hashable object (like lists) as keys.
my_dict = {'[1, 2, 3]': 'value'}
Error message:
TypeError: unhashable type: 'list'
Solution: Use a hashable object like strings or numbers as keys.
Why it happens: Lists are not hashable, so they cannot be used as dictionary keys.
How to prevent it: Convert the list to a string or number if necessary before using it as a key.
What causes it: Trying to access an attribute of a dictionary like it's a class instance.
print(my_dict.keys()) # Correct usage
print(my_dict.length) # Incorrect usage, triggers AttributeError
Error message:
AttributeError: 'dict' object has no attribute 'length'
Solution: Use dictionary methods like keys()
, values()
, and items()
instead of attributes.
Why it happens: Dictionaries are not classes, so they don't have class-specific attributes like length
.
How to prevent it: Familiarize yourself with the correct usage of dictionary methods.
my_dict['key']
.