Skip to content

Slicing Dictionary Python | Example code

  • by

Use the itertools islice function to slice the dictionary items() iterator in Python.

Example Slicing Dictionary Python

Simple example code. You have to import the itertools module to use the islice method in this program.

import itertools

d = {1: "A", 2: "B", 3: "C"}

res = dict(itertools.islice(d.items(), 2))

print(res)

Output:

Slicing Dictionary Python

How to slice a dictionary based on the values of its keys in Python?

Answer: You could use dictionary comprehension with:

d = {0: 1, 1: 2, 2: 3, 10: 4, 11: 5, 12: 6, 100: 7, 101: 8, 102: 9, 200: 10, 201: 11, 202: 12}
keys = (0, 1, 2, 100, 101, 102)
d1 = {k: d[k] for k in keys}

print(d1)

Output: {0: 1, 1: 2, 2: 3, 100: 7, 101: 8, 102: 9}

Do comment if you have any doubts and suggestions on this Python slicing topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading