Search code examples
pythondictionarydictionary-comprehension

Is it possible to assign variables inside of a dictionary comprehension?


I wrote a program to convert a nested dictionary containing a tuple of a string object and a dataframe. I don't wish to have a tuple object, just the dataframe object. So I wrote the following to get rid of the tuple object from my nested dictionary:

imported_dict = df_class.class_func(self)

keyList = imported_dict.keys()

newDict = dict.fromkeys(keyList)

for key in keyList:
     subkeyList = imported_dict[key].keys()
     newDict[key] = dict.fromkeys(subkeyList)
     
     for subkey in subkeyList:
         newDict[key][subkey] = imported_dict[key][subkey][1] #because I only want the dataframe

The above successfully generates the desired output which is a nested dictionary only containing a dataframe. My question is, can I do this using dictionary comprehension? I have attempted dictionary comprehension using a similar problem in the past. Each time I attempted to evaluate expressions like: subkeyList = imported_dict[key].keys() I received a syntax error. Is there a way to overcome this assignment limitation?

Edit:

The input of this is a dictionary which contains data similar to the follow:

{'A': {'1': (str obj, df obj),...,'12':(str obj, df obj)},..., 'Z': {'1': (str obj, df obj),...,'12':(str obj, df obj)}}

The desired outcome was:

{'A': {'1': [df obj],...,'12':[df obj]},..., 'Z': {'1': [df obj],...,'12':[df obj]}}

I was able to achieve this outcome. I would like to reproduce this same result using dictionary comprehension and avoiding syntax errors.


Solution

  • I could be mistaken, but it looks like your loop translates to this nested dictionary comprehension.

    You don't need dict.fromkeys() at all for any of this.

    newDict = {
        key: {
            subkey: subvalue[1]
            for (subkey, subvalue) in value.items()
        }
        for (key, value) in imported_dict.items()
    }
    

    The equivalent simple for loop construction is

    newDict = {}
    for key, value in imported_dict.items():
        newDict[key] = subDict = {}
        for subkey, subvalue in value.items():
            subDict[subkey] = subvalue[1]