Search code examples
pythonfor-comprehension

Syntax to modify the keys inside a dictionary for-comprehension


I am running into difficulties trying to create a modified key when manipulating a dictionary. Here the key needs to be changed from the original dict key to 'x' plus the dict key. How can that be done? My attempt is shown:

inventory = {k:updateMap(m,
                         {'partNumber': m['part'], 
                          'partName': m['desc'],
                          'bbox': {
                            'xmin' : bboxes[k].x,
                            'xmax' : bboxes[k].x + bboxes[k].w,
                            'ymin' : bboxes[k].y,
                            'ymax' : bboxes[k].y + bboxes[k].h
                          }
                          }) for k,m in 
                                ['x%d' %k1,m1 
                                 for k1,m1 in inventoryRaw.items()]}

Here is the syntax error Unresolved reference m1:

enter image description here

How should the nested comprehension be modified?


Solution

  • The problem here is the tuple needs to be explicitly spelled out :

    for k,m in [('x%s'%k1,m1) 
    

    This works:

    inventory = {'x%s'%k:updateMap(m,
                         {'partNumber': m['part'], 
                          'partName': m['desc'],
                         'objectClass': 'part',
                          'bbox': {
                            'xmin' : bboxes[k].x,
                            'xmax' : bboxes[k].x + bboxes[k].w,
                            'ymin' : bboxes[k].y,
                            'ymax' : bboxes[k].y + bboxes[k].h
                          }
                          }) for k,m in [('x%s'%k1,m1) 
                              for k1,m1 in 
                                    inventoryRaw.items()]}