How to slice a dictionary (e.g create a sub-dictionary or sample) in python ?


Examples of how to slice a dictionary (e.g create a sub-dictionary or sample) in python:

Create a dictionary

Lets first create a dictionary in python:

d = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6}

Slice a dictionary

Note: by default a dictionary is not an ordered object.

To select n elements of a dictionary, a solution is to do:

import itertools

dict(itertools.islice(d.items(), n))

where n <= len(d).

Example with 2

import itertools

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

returns here:

{'a': 1, 'b': 2}

Create a sample

To create a sample of a dictionary, a solution is to select randomly dictionary keys:

import random

d_keys = list(d.keys())

random.shuffle(d_keys)

d2 = {}
for key in d_keys:
    d2[key] = d[key]

dict(itertools.islice(d2.items(), 2))

returns for example

{'c': 3, 'a': 1}

References