在Python中高效地迭代字典 [英] Efficiently iterating a dictionary in Python

查看:53
本文介绍了在Python中高效地迭代字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这就是问题所在,我要导入一个字典,其中包含6000到12000个键的任意位置.然后使用嵌套的for算法将它们分组到另一个词典中的列表中.我正在使用以下代码检查密钥是否在字典中:

So here's the problem, I'm importing a dictionary with anywhere from 6000 to 12000 keys. Then using a nested for algorithm to group them into a list inside of another dictionary. I'm using the following code to check if the key is in the dictionary:

for key in range(sizeOfOriginalKeys):
    if key in key_data:

您可能会想到,由于排序算法相当复杂,因此这将永远花费很多.我只想遍历"key_data"中的键,而不必进行1000到11999检查字典中是否有该键.有没有办法列出当前密钥?然后遍历它们吗?还是至少比我目前正在做的事更有效率?

As you might imagine, this is taking forever since the sorting algorithm is fairly complex. I would like to only iterate through the keys in 'key_data', without doing 1000 to 11999 checks if there is that key in the dictionary. Is there a way to make a list of current keys? Then iterate through them? Or at least something more efficient than what I'm currently doing?

凯文建议后的当前代码:

Current Code after Kevin's suggestion:

for key in key_data:
    currentKey = key_data[key].name
    if key_data[currentKey].prefList[currentPref] == currentGroup
        key_data[currentKey].currentScore = getDotProduct()
        group_data[currentGroup].keyList.append(key_data[currentKey])
        group_data[currentGroup].sortKeys()
        del key_data[currentKey]

键名是整数.在排序算法的最后,如果密钥已被分组,则删除该密钥.现在我得到一个错误:字典在迭代过程中更改了大小.

The key names are integers. At the end of the sorting algorithm I delete the key, if its been sorted into a group. Now I get an error: dictionary changed size during iteration.

有什么想法吗?

推荐答案

您正在尝试:

for key in key_data:

这篇关于在Python中高效地迭代字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆