Examples of how to slice a dictionary (e.g create a sub-dictionary or sample) in python:
Table of contents
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 itertoolsdict(itertools.islice(d.items(), n))
where n <= len(d).
Example with 2
import itertoolsdict(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 randomd_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}
