簡體   English   中英

詞典理解內的詞典理解

[英]Dictionary Comprehension inside a Dictionary Comprehension

我的以下輸出來自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"
            ]
        }
    ]
},

我正在嘗試通過運行字典理解來清理它。 在條件語句中添加第二個理解之前,我一直很好。

{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}

我得到的錯誤是:

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

當條件只是item ['conditions']時,它運行良好,但是我想即時替換label的值,我想我試圖變得太聰明,或者我遺漏了一些明顯的東西。 我知道如果條件沒有可能包含多個項目,那么我就不需要第二個理解了。

當我碰到這堵牆時,任何幫助將不勝感激。

編輯:添加了錯誤消息

看一下你內心的理解(為簡潔起見,x,y,z):

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

您嘗試一次理解多個鍵/值對,但這沒有意義。 我想你想寫:

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

我發誓我在這里看到一條評論,要求獲得我提出問題后立即發布的預期輸出,但是我在這里不再看到它。 編寫輸出使我意識到我在錯誤條件下想到了這些項目。 我將其包裝在一個列表中,現在有一個字典列表,它可以正常工作。

{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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM