Python Dictionaries: Accessing Values and Understanding Dictionary Slicing
Python Programming Tutorial for Students
In this lesson, we will learn how to create a Python dictionary, access
values using dictionary keys, and understand why dictionary slicing such as
d['bar':'baz'] produces an error.
1. What is a Dictionary in Python?
A dictionary is a Python data structure that stores data as key-value pairs.
For example:
d = {'foo': 100, 'bar': 200, 'baz': 300}
In this dictionary:
'foo'is a key and100is its value.'bar'is a key and200is its value.'baz'is a key and300is its value.
The dictionary can be visualized as:
| Key | Value |
|---|---|
| foo | 100 |
| bar | 200 |
| baz | 300 |
2. Accessing a Dictionary Value
To access a value in a dictionary, place the key inside square brackets
[].
d = {'foo': 100, 'bar': 200, 'baz': 300}
print(d['bar'])
print(d['baz'])
The output is:
200
300
When Python sees:
d['bar']
it searches the dictionary for the key 'bar' and returns its
corresponding value, which is 200.
3. What Happens If We Try to Slice a Dictionary?
Students who are familiar with lists and strings may try something like:
d['bar':'baz']
However, this is not valid dictionary syntax.
Python interprets 'bar':'baz' as a slice.
Dictionaries do not support slicing in this way.
You may therefore see an error similar to:
KeyError: slice('bar', 'baz', None)
4. Why Does This Error Occur?
Slicing is commonly used with sequences such as lists, strings and tuples.
For example:
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
Output:
[20, 30, 40]
Here, [1:4] means "give me the elements starting from index
1 up to, but not including, index 4."
A dictionary, however, is normally accessed using its keys, not by slicing between keys.
5. Correct Way to Retrieve Multiple Dictionary Entries
If you want the values associated with 'bar' and
'baz', you can access them individually:
d = {'foo': 100, 'bar': 200, 'baz': 300}
print(d['bar'])
print(d['baz'])
Output:
200
300
6. Selecting Several Specific Keys
We can also create a new dictionary containing only the keys we want:
d = {'foo': 100, 'bar': 200, 'baz': 300}
result = {key: d[key] for key in ['bar', 'baz']}
print(result)
Output:
{'bar': 200, 'baz': 300}
7. If You Really Want to Slice Dictionary Entries
You can first convert the dictionary's items into a list and then use normal list slicing.
d = {'foo': 100, 'bar': 200, 'baz': 300}
print(list(d.items())[1:3])
Output:
[('bar', 200), ('baz', 300)]
Notice that we used list(d.items()) first. This converts the
dictionary's key-value pairs into a list, and lists support slicing.
8. Important Difference to Remember
| Expression | Meaning | Result |
|---|---|---|
d['bar']
|
Access the value using the key bar
|
200 |
d['baz']
|
Access the value using the key baz
|
300 |
d['bar':'baz']
|
Attempts dictionary slicing | ❌ Error |
list(d.items())[1:3]
|
Converts items to a list and slices the list | ✅ Works |
9. Complete Example
# Creating a dictionary
d = {'foo': 100, 'bar': 200, 'baz': 300}
# Accessing individual values
print(d['bar'])
print(d['baz'])
# Selecting dictionary items by position
print(list(d.items())[1:3])
Output:
200
300
[('bar', 200), ('baz', 300)]
Key Takeaway for Students
Dictionary → access values using keys.
List/String/Tuple → can be sliced using positions.
10. Practice Exercise
Create the following dictionary:
student = {
'name': 'John',
'age': 20,
'department': 'Computer Engineering',
'level': 300
}
Then write Python code to:
- Print the student's name.
- Print the student's age.
- Print the student's department.
- Print the student's level.
- Try using a slice such as
student['age':'level']and observe the error.
Conclusion
Python dictionaries are designed around key-value pairs.
To retrieve a value, use its key inside square brackets, such as
d['bar'].
Unlike lists, strings and tuples, dictionaries do not support traditional
slicing such as d['bar':'baz']. If you need to select entries
by position, you can convert the dictionary items to a list first.
Python Programming Tutorial
Learn • Practice • Build
Comments
Post a Comment