简体   繁体   中英

Dictionary Comprehension inside a Dictionary Comprehension

I have the output below coming from a REST API:

{
    "internalId": 14,
    "label": "L1",
    "requiredLevel": 10,
    "preferableLevel": 100,
    "conditions": [
        {
            "label": "A_WO_TYPE",
            "function": "in",
            "valueList": [
                "T1",
                "T2",
                "T3",
                "T4"
            ]
        },
        {
            "label": "A_SYS_AREA",
            "function": "in",
            "valueList": [
                "9999"
            ]
        }
    ]
},

I'm trying to clean it up by running a dictionary comprehension. I was doing fine until I added a second comprehension inside the conditions statement.

{item['label']: 
    {'requiredLevel': item['requiredLevel'], 
    'preferableLevel': item['preferableLevel'],
    'conditions': 
        {'label': LABEL_REPLACEMENT[condition['label']],
        'function': condition['function'],
        'valueList': condition['valueList']
        for condition in item['conditions']}}
for item in tempItems}

The error I get is:

for condition in item['conditions']}
  ^
SyntaxError: invalid syntax

It was running fine when conditions was just item['conditions'] but i wanted to replace the value of label on the fly and I think I tried to get too clever or I'm missing something obvious. I know if conditions didn't have the possibility of having multiple items in it, i wouldn't need the second comprehension.

Any help would be greatly appreciated as I'm hitting a wall on this one.

Edit: Added error msg

Look at your innermost comprehension (x, y, z for brevity):

{'label': x, 'function': y, 'valueList': z for condition in item['conditions']}

You try to cerate multiple key/value pairs in one comprehension, which doesn't make sense. I think you wanted to write:

[{'label': x, 'function': y, 'valueList': z } for condition in item['conditions']]

I swear I saw a comment on here asking for the expected output that was posted as soon as I asked the question but I don't see it here anymore. Writing the output made me realize I was thinking of the items in conditions wrong. I wrapped it in a list and now I have a list of dictionaries and it works.

{item['label']: 
    {'requiredLevel': item['requiredLevel'], 
    'preferableLevel': item['preferableLevel'],
    'conditions': 
        [{'label': LABEL_REPLACEMENT[condition['label']],
        'function': condition['function'],
        'valueList': condition.get('valueList',condition.get('value',None))}
        for condition in item['conditions']]}
for item in tempItems}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM