Search code examples
pythondictionarykeydefaultdict

Error Changing Dictionary Keys


I've two defaultdicts I eventually want to merge, but first I need to make their keys match. According to some threads I've seen here, I can use pop() to replace keys in a dictionary. But that only updates the existing dictionary, whereas I want to create a new dictionary with the new keys. So something like:

existing_dict_one -> new_dict_one

This is what I've so far:

def split_tabs(x):
    """
    Function to split tab-separated strings, used to break up the keys that are separated by tabs.
    """
    return x.split('\t')


def create_dict(old_dict):
    """
    Function to create a new defaultdict from an existing defaultdict, just with
    different keys.
    """
    new_dict = old_dict.copy()  # Create a copy of old_dict to house the new keys, but with the same values.
    for key, value in new_dict.iteritems():
        umi = split_tabs(key)[0]  # Change key to be UMI, which is the 0th index of the tab-delimited key.
        # new_key = key.replace(key, umi)
        new_dict[umi] = new_dict.pop(key)
    return new_dict

However, I'm getting the following error

RuntimeError: dictionary changed size during iteration

and I don't know how to fix it. Does anyone know how to correct it? I'd like to use the variable "umi" as the new key.

I'd like to post the variable "key" and dictionary "old_dict" I'm using for testing this code, but it's messy and takes up a lot of space. So here's a pastebin link that contains them instead.

Note that "umi" comes from variable "key" which is separated by tabs. So I split "key" and get the first object as "umi".


Solution

  • Just use a dict comprehension for this:

    new_dict = {split_tabs(key)[0]: value for key, value in old_dict.iteritems()}
    

    Trying to modify a dictionary while iterating over it is not a good idea in general.