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

August 07, 2021    /    Viewed: 399    /    Comments: 0    /    Edit


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


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!