Kodeclik Logo

Our Programs

Courses

Learn More

Schedule

Kodeclik Blog

How to slice a dictionary in Python

Consider a simple dictionary in Python like so:

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}

Slicing is the act of taking a subset of this dictionary to create a smaller, new, dictionary.

Note that dictionaries are by definition unordered even though they are specified in some order and printed in a given order. So it doesn’t make sense to say the “2nd element of the dictionary”, or “the last element of the dictionary”. So what does slicing mean?

Slicing a dictionary in Python

There are potentially two meanings of the word slicing here. First, we can convert the dictionary into a list, slice the list, and convert the list back to a dictionary. Alternatively, we can take a subset of elements from the dictionary satisfying some condition. Lets look at each of these approaches next!

Method 1: Convert a dictionary to a list and back

In this approach, we first convert a dictionary into a list, like so:

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}
  
print(calendar)
calendar_list = list(calendar.items())
print(calendar_list)

The output here is:

{'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 
'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 
'November': 30, 'December': 31}
[('January', 31), ('February', 28), ('March', 31), ('April', 30), 
('May', 31), ('June', 30), ('July', 31), ('August', 31), 
('September', 30), ('October', 31), ('November', 30), ('December', 31)]

Note that the first output is of the dictionary (and thus has assignments of values to keys) and the second output is of the list (and thus has a list of tuples, each tuple denoting a key and value).

Once we have it as a list, we can slice it the usual way and then convert it back to a list. Here is how that works:

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}
  
print("Original dictionary:")
print(calendar)
print()

print("Dictionary converted to a list:")
calendar_list = list(calendar.items())
print(calendar_list)
print()

print("Sliced list:")
sliced_calendar_list = calendar_list[4:8]
print(sliced_calendar_list)
print()

print("Sliced dictionary:")
print(dict(sliced_calendar_list))
print()

The output will be:

Original dictionary:
{'January': 31, 'February': 28, 'March': 31, 'April': 30, 
'May': 31, 'June': 30, 'July': 31, 'August': 31, 'September': 30, 
'October': 31, 'November': 30, 'December': 31}

Dictionary converted to a list:
[('January', 31), ('February', 28), ('March', 31), ('April', 30), 
('May', 31), ('June', 30), ('July', 31), ('August', 31), 
('September', 30), ('October', 31), ('November', 30), 
('December', 31)]

Sliced list:
[('May', 31), ('June', 30), ('July', 31), ('August', 31)]

Sliced dictionary:
{'May': 31, 'June': 30, 'July': 31, 'August': 31}

As you can see the slicing operator retains only the summer months (through our use of indices from 4 to 7). Then this list is converted back to a dict using the dict() constructor. In this way we have sliced the original Python dictionary.

Method 2: Select items from a dictionary satisfying some condition using dictionary comprehension

The second way to slice a dictionary is to provide some condition, either on the keys or values (or both, if necessary). Let us try to find those dictionary elements where the number of days is less than 30.

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}
  
print(calendar)
sliced_calendar = { k: v for (k,v) in calendar.items() if v < 30}
print(sliced_calendar)

In the above code, we are using a dictionary comprehension to construct “sliced_calendar”. This line says that the dictionary comprehension consists of mappings “k” to “v” where (k,v) are sourced from calendar (using calendar.items()) with a further check that the number of days (i.e., v) must be less than 30.

The output is:

{'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 
'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 
'November': 30, 'December': 31}
{'February': 28}

Note that in this code all operations are being performed on dictionaries; we are not converting them to lists (and back).

As another example, let us slice the dictionary to find those elements where the month contains “u”:

calendar = {'January': 31,
            'February': 28,
            'March': 31,
            'April': 30,
            'May': 31,
            'June': 30,
            'July': 31,
            'August': 31,
            'September': 30,
            'October': 31,
            'November': 30,
            'December': 31}
  
print(calendar)
sliced_calendar = { k: v for (k,v) in calendar.items() if "u" in k}
print(sliced_calendar)

Here the dictionary comprehension uses the key information and checks if the letter u is a substring of k. The output is:

{'January': 31, 'February': 28, 'March': 31, 'April': 30, 'May': 31, 
'June': 30, 'July': 31, 'August': 31, 'September': 30, 'October': 31, 
'November': 30, 'December': 31}
{'January': 31, 'February': 28, 'June': 30, 'July': 31, 'August': 31}

In other words, January, February, June, Jully, and August are the only months satisfying our condition.

Thus, we have learnt two ways to slice a dictionary: either convert them to lists so we can use indices, or use conditions on either keys or values to subset items from the dictionary. Which approach is your favorite?

If you liked this blogpost, checkout our blogpost on comparing two dictionaries. Also learn how to unpack a dictionary into variables.

For more Python content, checkout the math.ceil() and math.floor() functions! Also
learn about the math domain error in Python and how to fix it!

Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2024. All rights reserved.