简体   繁体   English

如何从 Python 中的字典中删除随机多余的键和值

[英]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:我试着用这段代码只保留 10 个第一键:

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. Select 先删除一些随机键,然后遍历该列表并删除它们。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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