简体   繁体   中英

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 (ie 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?

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

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM