如何删除具有多个值的dict列表中的项目,如果值相同

时间:2018-03-13 13:11:09

标签: python list dictionary key delete-row

1个数据库中的机器列表

>netbox_list = 
               [{'mac_address': '00:00:00:5B:A4:57', 'device_id': '607', 
              'ip_address': '10.11.2.2'},
               {'mac_address': '00:00:00:5B:A4:51', 'device_id': '608', 
               'ip_address': '10.11.2.3'},
               {'mac_address': '00:00:00:8C:DB:71', 'device_id': '156', 
               'ip_address': '10.11.2.21'}]

2个数据库中的机器列表

>infoblox_list = 
               [{'mac_address': '00:00:00:5B:A4:51', 'ip_address': '10.11.2.3'},
               {'mac_address': ''00:00:00:5B:A4:57', 'ip_address': '10.11.2.2'},
               {'mac_address': ''00:00:00:8C:DB:70', 'ip_address': '10.11.2.20'},
               {'mac_address': ''00:00:00:8C:DB:80', 'ip_address': '10.11.2.22'}]

>netlen = len(netbox_list)
>infolen = len(infoblox_list)
>#difflist = netbox_list

# Objective is to create a list of dict where the 'ip_address' don't match
#Comparing the dicts with values to delete it from the list
>for i in range(netlen):
    for j in range (infolen):
      if netbox_list[i]['ip_address'] == infoblox_list[j]['ip_address']:
        del netbox_list[i]
        break
print(netbox_list)


'''
  

错误:       Traceback(最近一次调用最后一次):         文件“C:/ Python / Flask / until now.py”,第53行,in           if netbox_list [i] ['ip_address'] == infoblox_list [j] ['ip_address']:       IndexError:列表索引超出范围'''

1 个答案:

答案 0 :(得分:0)

netbox_list_set = set([x['ip_address'] for x in netbox_list])
infoblox_list_set = set([x['ip_address'] for x in infoblox_list])
unmatched_ips = netbox_list_set - infoblox_list_set