How to slice dictionary in Python? [SOLVED]


Python

Introduction

In this article, we will see one of the most asked and confusing problems: slicing a dictionary in Python. Slicing a dictionary means obtaining the subsets of the dictionary using the key-value pairs. There are many ways to do that but those techniques are lengthy and confusing, we are going to use a module known as itertools, using this module, slicing a dictionary is very easy. We will see each and everything with the help of examples. Let’s get started.

 

What is a python dictionary?

Dictionary in python is an unordered and mutable container that is used to store data using key-value pairs. This is one of the four major data types in python. We store values using keys and we can retrieve those values by their specified key. We use curly ({}) braces to initialize the dictionary in python. Let’s see an example:

dictionary = {'key':'value'}

The syntax is easy, we specify a key and then assign a value to the key. This way, the data is stored very easily and can be retrieved easily.

student = {'RNo' : 10, 'Marks' : 90, 'Percentage' : 90}
print(student)

Output:

{'RNo': 10, 'Marks': 90, 'Percentage': 90}

We have initialized a dictionary above, you can see that we are giving a key and then assigning a value to the key. Now let’s see how to slice it very easily.

 

Slicing dictionary in Python

We know what slicing a dictionary is. To slice a dictionary, we can use multiple ways but itertools is one of the best modules which helps us to slice dictionaries very easily in python. The itertools is used to manipulate data structures in python, and it is used to iterate through different data structures. This module is very fast, efficient, and easy to use. This module is part of Python’s standard libraries so you don’t need to install it separately. Let’s use this with the help of some examples:

 

Example 1: Using itertools

import itertools
student = {'RNo' : 10, 'Marks' : 90, 'Percentage' : 90}
new_dict = dict(itertools.islice(student.items(), 2))
print(new_dict)

Output:

{'RNo': 10, 'Marks': 90}

We have imported itertools, then a dictionary is defined. We are making a new dictionary with the help of dict() function and storing a slice of the first dictionary in it. We are using the islice() function and passing our original dictionary to it, we are also specifying the index of the dictionary we are interested in a slice. And boom, we sliced the dictionary.

 

Example 2: Using itertools

Let’s see another example by making a small change to the code.

import itertools
student = {'RNo' : 10, 'Marks' : 90, 'Percentage' : 90}
new_dict = dict(itertools.islice(student.items(), 1,3))
print(new_dict)

Output:

{'Marks': 90, 'Percentage': 90}

We have sliced the same dictionary but this time, we pass two values to the islice() function. 1 and 3 mean that leave the value on index 1 and take 2 and 3 indexes.

 

Example 3: Using for loop

languages = {1 : 'Python', 2 : 'Java', 3 : 'C++', 4 : 'C#', 5 : 'Dart'}
keys = (1,2,5)
favorite_langs = { i : languages[i] for i in keys}
print(favorite_langs)

Output:

{1: 'Python', 2: 'Java', 5: 'Dart'}

This example is very interesting. We are not using itertools this time, instead, we are using a for loop. We have initialized a dictionary of different programming languages, we have another variable keys which have all the keys we are interested in. Then we are using a for loop and pass the keys, this way, a dictionary can be sliced. That’s all for today.

Thank you!

 

Summary

In this article, we saw how to slice a dictionary in python using itertools and using a for loop. Dictionaries are a powerful data structure in python, we saw how to initialize a dictionary and how to manipulate it.

 

Deepak Prasad

Deepak Prasad

He is the founder of GoLinuxCloud and brings over a decade of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive experience, he excels in various domains, from development to DevOps, Networking, and Security, ensuring robust and efficient solutions for diverse projects. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment