[英]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']
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
的值取out1
或out2
的值作為
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.