0

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?

Abhyuday Vaish
  • 2,357
  • 5
  • 11
  • 27
Michael
  • 45
  • 3
  • 2
    This seems to be roughly what you want to accomplish: https://stackoverflow.com/a/47704499/13526701 – NoBlockhit Apr 26 '22 at 14:15
  • 1
    NoBlockhit's recommendation is probably best. If you want to "*temporarily"* reduce the size, removing elements means you might have to add them back in later to maintain the correct behavior. – Alexander L. Hayes Apr 26 '22 at 14:18

3 Answers3

2

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

dict(list(dict1.items())[:10])
Elger
  • 136
  • 8
1

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)
Deusy94
  • 733
  • 3
  • 13
1

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])
Don
  • 164
  • 3