我有字典:
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 :(得分:2)
您可以使用列表理解(pythonic方式构建列表),如
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']