简体   繁体   中英

Efficiently iterating a dictionary in Python

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:

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.

Thoughts?

您正在努力:

for key in key_data:

You can try

for key,value in key_data.items() :
    print key
    print value

you can access to value without calling key_data[key]

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