Search code examples
pythonpython-3.xdictionarydictionary-comprehension

I want to clean a nested dictionary python using dictionary comprehension or for loops


I have a nested dictionary which contains a series of keys Dictionary_ABC = {'ABC 1':..., 'ABC 2': ..., ..., 'ABC N':...}. Each of these keys contains random values not associate with the ABC keys, but also others that are. For example:

Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE, ..., 'ABC N': NONE}}

In the sub dictionary 'ABC 1', I would like to delete all ABC values which do not contain 'ABC 1'. So the end result should be something like this:

Dictionary_ABC['ABC 1'] = {'ABC 1': {'ZYZZ': NONE, 'DAFDZ': NONE, 'EASDF': NONE, 'ABC 1': NONE}}

All of the other ABC #'s should fall off and I am just left with the other subkeys and the one that matches the primary key.

I've tried many different solutions, but the one that seems to produce the closest result is:

Dictionary_ABC_Copy = {}
for key in Dictionary_ABC:
   for subkey in Dictionary_ABC[key]:
       if this criteria met:
           if this next criteria met:
                pass #I don't want to copy this
           else:
                Dictionary_ABC_Copy[key] = subkey #copy if it doesn't fit both criteria
        else:
            Dictionary_ABC_Copy[key] = subkey #because I want to copy this
       

The criteria are producing the necessary result, however whenever I attempt to update the dictionary or use the method above, the dictionary overwrites all the previous values. I would simply like to update keys with these values if they don't pass to the filter criteria. This is my first question.

My second question is there a better way to do this? I hope that I have provided the material the information necessary to help answer these questions.

Thanks.


Solution

  • I think you want something like this:

    dictionary_abc_copy = {
       abc: {k: v for k, v in inner.items() if not k.startwith('ABC ') or k == abc}
       for abc, inner in dictionary_abc.items()
    }