'How to remove random excess keys and values from dictionary in Python

I have a dictionary variable with several thousands of items. For the purpose of writing code and debugging, I want to temporarily reduce its size to more easily work with it (i.e. check contents by printing). I don't really care which items get removed for this purpose. I tried to keep only 10 first keys with this code:

i = 0
for x in dict1:
    if i >= 10:
        dict1.pop(x)
    i += 1

but I get the error:

RuntimeError: dictionary changed size during iteration

What is the best way to do it?



Solution 1:[1]

You could just rewrite the dictionary selecting a slice from its items.

dict(list(dict1.items())[:10])

Solution 2:[2]

Select some random keys to delete first, then iterate over that list and remove them.

import random
keys = random.sample(list(dict1.keys()), k=10)
for k in keys:
    dict1.pop(k)

Solution 3:[3]

You can convert the dictionary into a list of items, split, and convert back to a dictionary like this:

splitPosition = 10    
subDict = dict(list(dict1.items())[:splitPosition])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Elger
Solution 2 Deusy94
Solution 3 Don