簡體   English   中英

如何通過檢查字典中映射的鍵來獲取字典中的值

[英]How to fetch the value in dictionary by checking the key mapped in the dict

字典在下面

my = {
  "1": {
    "exclude": 'A,B',
    "column": "value",
    "output": "Out1",
    "Out1": "Cost",
    "Out2": "Rev"
  },
  "2": {
    "exclude": 'None',
    "column": "value",
    "output": "Out2",
    "Out1": "Cost",
    "Out2": "Rev"
  }
}
  • 我需要檢查列鍵值(如果較低(我的[列]))==較低(值)
  • 我有exclude_list = ['A','B','C']
  • 我需要排除鍵,如果排除是 'A' 檢查exclude_list = ['A','B','C']取值B,C 如果排除鍵是“A,B”,則取值C ,如示例中所示。
  • 如果output鍵是Out1我需要檢查output鍵,然后獲取Out1值並映射到EndOutput

預期輸出

{'1': {'exclude': ['C'], 'EndOutput': 'Cost'},
 '2': {'exclude': ['A', 'B', 'C'], 'EndOutput': 'Rev'}}

exclude_list = ['A','B','C']
for k,v in my.items():
    if v['column'].lower() == 'value'.lower:
     
   

您可以for e in my:使用for e in my:迭代鍵 1,2 .. N,然后在set()差異的幫助下計算 exclude 為

並提取這樣的東西

 exc = set(['A','B','C']) - set(my[e]["exclude"].split(",") if len(my[e]["exclude"].split(",")) else [] )

接下來,您可以根據output的值取out1out2的值作為

my[e][my[e]["output"]]

在新字典中插入為

newdict[e] = {'exclude': list(exc) ,'EndOutput':my[e][my[e]["output"]]}

總的來說,這是您可以迭代的方式

newdict = {}
for e in my:
     if my[e]['column'].lower() == 'value':
             exc = set(['A','B','C']) - set(my[e]["exclude"].split(",") if len(my[e]["exclude"].split(",")) else [] )
             newdict[e] = {'exclude': list(exc) ,'EndOutput':my[e][my[e]["output"]]}

打印 newdict 將產生此輸出

'1': {'EndOutput': 'Cost', 'exclude': ['C'] },
'2': {'EndOutput': 'Rev', 'exclude': ['A', 'B', 'C'] }}

暫無
暫無

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

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