2014-04-10 104 views
0

我有詞典:如何檢查字典項目是否在列表中? PYTHON

data_portgroup = {"data_portgroup" : ["DataPortGroup1", "DataPortGroup2"]} 
mgmt_portgroup = {"mgmt_portgroup" : ["MgmtPortGroup1", "MgmtPortGroup2"]} 
trunk_portgroup = {"trunk_portgroup" : ["TrunkPortGroup1", "TrunkPortGroup2"]} 

而且我有一個列表:

portgroups = ["VM Network", 
"VMPortGroup1", 
"DataPortGroup1", 
"f7b64e53-cdb0-4bb6-b479-8c8aa6a5ab10", 
"TrunkPortGroup1", 
"dvSwitch-DVUplinks-232", 
"MgmtPortGroup1", 
"dvPortGroup", 
"dvSwitchOVSvApp-DVUplinks-69", 
"dvSwitchBootVMs-DVUplinks-61" 
] 

現在我想查詞典值出現在列表中?

+0

你似乎有你提到的「字典」多個詞典,我假設你想檢查他們所有的? –

+0

你的問題不明確。什麼是預期的輸出? – thefourtheye

+0

是,對於每個data_portgroup「DataPortGroup1」存在於列表中或不存在。以同樣的方式將檢查下一個字典。 – Amby

回答

2

您可以使用列表理解(Python的方式來構建列表)像

found_in_data_portgroup = [pg for pg in portgroups if pg in data_portgroup["data_portgroup"]] 
found_in_mgmt_portgroup = [pg for pg in portgroups if pg in mgmt_portgroup["mgmt_portgroup"]] 
found_in_trunk_portgroup = [pg for pg in portgroups if pg in trunk_portgroup["trunk_portgroup"]] 

print found_in_data_portgroup 
print found_in_mgmt_portgroup 
print found_in_trunk_portgroup 

獲得

['DataPortGroup1'] 
['MgmtPortGroup1'] 
['TrunkPortGroup1'] 
+0

非常好!我在寫理解,但在幾秒鐘內得到了有效的答案。 – Amby

相關問題