Search code examples
pythondictionaryfor-loopdictionary-comprehension

dictionary comprehension in Python


Is there a way to the follwing in dictionary comprehension?

bmcdsreg = {}
for key, val in bms.iteritems():
    bmcdsreg[key] = {}
    for reg in bmmaps.columns:
        bmcdsreg[key][reg]= val*bmmaps[reg]

I have the following version where the keys are interchanged:

bmcdsreg = {reg: {key: val*bmmaps[reg] for key, val in bms.iteritems()}
             for reg in bmmaps.columns}

Solution

  • Here is how:

    bmcdsreg = {
        key: {reg: val * bmmaps[reg] for reg in bmmaps.columns}
        for key, val in bms.items()
    }