我有一个列表和一个字典,仅需通过按键进行比较。 该列表由手工创建,用于定义在以下过程中将使用哪些Vars。该列表将用于将结果写入CSV列表=标题中。
某些设备不支持所有Var,并且不会在响应中将其发送回。
base=["General.IpAddress", "General.ActualHostname", "General.UserLabel1", "General.UserLabel2"]
response_diff='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217"}'
您看到响应中缺少General.UserLabel1
和General.UserLabel2
。 (可能会缺少更多的变量)
因此,我必须在响应中添加缺少NULL值的Vars。
答案 0 :(得分:0)
import json
from pprint import pprint
def compare_ListWithDict(list_base,dict_ref):
#temp dict
dict_base_tmp = {}
dict_ref = dict_ref.lower()
#run thru List an generate an dict with Value 0 for every Key
for item in list_base:
dict_base_tmp[item.lower()] = 0
#load dict_ref as JSON
dict_ref_json=json.loads(dict_ref)
#get len
dict_base_len= len(dict_base_tmp)
dict_ref_len= len(dict_ref_json)
#if lens are equal return the dict_ref (response from Device)
if dict_base_len == dict_ref_len:
return dict_ref_json
else:
#run thru list_base and search for keys they AREN'T in dict_ref_json
#if missing key is found, add the key with Value NULL to the dict_ref_json
for item in list_base:
if not item.lower() in dict_ref_json.keys():
item_lower = item.lower()
dict_ref_json[item_lower]='null'
return dict_ref_json
base=["General.IpAddress", "General.ActualHostname", "General.UserLabel1", "General.UserLabel2"]
response_diff='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217"}'
response_equal='{"general.actualhostname":"ST_38_217","general.ipaddress":"192.168.38.217","general.userlabel1":"First Label", "general.userlabel2":"Second Label"}'
结果:
pprint(compare_ListWithDict(base,response_equal))
#base and response are equal by the keys
{'general.actualhostname': 'st_38_217',
'general.ipaddress': '192.168.38.217',
'general.userlabel1': 'first label',
'general.userlabel2': 'second label'}
pprint(compare_ListWithDict(base,response_diff))
#base and response is different by the keys
{'general.actualhostname': 'st_38_217',
'general.ipaddress': '192.168.38.217',
'general.userlabel1': 'null',
'general.userlabel2': 'null'}