Home > Mobile >  How to remove random excess keys and values from dictionary in Python
How to remove random excess keys and values from dictionary in Python

Time:04-27

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?

CodePudding user response:

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

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

CodePudding user response:

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)

CodePudding user response:

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])
  • Related