python slice dictionary

PHOTO EMBED

Tue Dec 13 2022 19:47:27 GMT+0000 (Coordinated Universal Time)

Saved by @tofufu #python #dictionary

# Import the itertools library 
# This library ships with Python 3 so you don't have to download anything
# It provides a bunch of tools for dealing with sequences and iteration
import itertools

# Create a new dictionary variable
myDictionary = {
    "name": "Fred",
    "animal": "cat",
    "colour": "red",
    "age": 3
} 

# Create a sliced dictionary
# dict() is used to convert the iterable result of itertools.islice() to a new dictionary
slicedDict = dict(itertools.islice(myDictionary.items(), 1 ,3))

print(slicedDict)

# Prints out 
# {   
#     'animal': 'cat', 
#     'colour': 'red'
# }
content_copyCOPY

https://www.linuxscrew.com/python-dictionary-slice