在Python中比较两个字典与不同的键?
问题描述:
我有两个包含IP地址的字典。例如在Python中比较两个字典与不同的键?
site_scope1 = {'Servers': ['1.1.1.1', '1.1.1.2']}
,另一个包含从它看起来像
vlan_helpers = {'300': ['1.1.1.1', '1.1.2.2']}
的设备拉到地址我如何比较两个库,以便验证vlan_helpers的300项中包含的服务器密钥值在site_scope1?
答
要检查这两个键具有相同的值,就可以直接访问它们并做这样比较:
if site_scope1['Servers'] == vlan_helpers['300']:
# Do something.
如果您只想检查服务器列表中的某些密钥是否也位于300列表中,则可以这样做:
for item in site_scope1['Servers']:
if item in vlan_helpers['300']:
print('IP is in Both dicts: ', item)
答
你可以找到它的Serveurs
在300
:
>>> site_scope1 = {'Servers': ['1.1.1.1', '1.1.2.2']}
>>> vlan_helpers = {'300': ['1.1.1.1', '1.1.2.2']}
>>> [x for x in site_scope1['Servers'] if x in vlan_helpers['300']]
['1.1.1.1', '1.1.2.2']
>>> site_scope1 = {'Servers': ['1.1.1.1', '1.1.1.2']}
>>> vlan_helpers = {'300': ['1.1.1.1', '1.1.2.2']}
>>> [x for x in site_scope1['Servers'] if x in vlan_helpers['300']]
['1.1.1.1']
答
当我明白你的问题,你只是想比较一下字典两个specific
元素。
site_scope1 = {'Servers': ['1.1.1.1', '1.1.1.2']}
vlan_helpers = {'300': ['1.1.1.1', '1.1.2.2']}
print(site_scope1['Servers'] == vlan_helpers['300'])
输出:
False
如果您的IP的不下令使用set()
:
print(set(site_scope1['Servers']) == set(vlan_helpers['300']))`