如何从嵌套的字典中过滤和读取值和键?



我目前正在研究一个python脚本,理论上应该读我一个YAML文件(hostname_list),并将内容保存为一个嵌套的字典(称为相同)。在下一步中,它应该循环遍历第二个字典的所有键(参见下面的示例),并在第三个字典中检查键&;severity&;如果键有一定的值在开始时的参数中给出。如果该参数与特定字典中的值相同,则应该以json格式将第二个字典的键以及第三个字典的所有键和值打印到控制台。

我的字典:

{"sap_landscape":  #dict1
{"dctr1440":  #dict2
{"hostname": "dctr1440", "SID": "TT", "Type": "Spo",  #dict3
"Landscape": "RFK", "Severity": "SX", "Username": "adm", 
"UserID": 93, "Global": null, "Cycle": 1}, 
"dctr1091": {"hostname": "dctr1091", "SID": "TT", "Type": "Spo", "Landscape": 
"RFK", "Severity": "SX", "Username": null, "UserID": null, 
"Global": null, "Cycle": 2}, 
"dctr1512": {"hostname": "dctr1512", "SID": "TT", "Type": "C", 
"Landscape": "RFK", "Severity": "SBX", "Username": null, 
"UserID": null, "Global": null, "Cycle": 1}, 
"dctr193": {"hostname": "dctr193", "SID": "TT", "Type": "I", "Landscape": 
"RFK", "Severity": "SX", "Username": null, "UserID": null, 
"Global": null, "Cycle": 2}

到目前为止我写的代码:

def main(severity):
with open(filename) as infile:
hostname_list = yaml.safe_load(infile)
for k in hostname_list['sap_landscape'].keys():           # i don't know if that is correct 
for s in hostname_list['sap_landscape'][k].items():     since i am clueless what to do 
after i read the file and saved it 
as a dict

很抱歉,如果这不是很多工作,但我是一个非常新的python和挣扎字典相当多。如果你有一个解决方案,并且有一点时间,如果你能写一个简短的描述,说明你是如何/为什么你这样做的,因为我想从我的错误中吸取教训。

提前感谢:)

可以这样做:

for k1, v1 in hostname_list['sap_landscape'].items():
for k2, v2 in v1.items():
if k2 == "Severity" and v2 == "The value that you want":
print(k1) # to print key name of second dict
print(v1) # to print contents of that dict

在此解中,k1为原字典的每个键,v1为对应的值(即字典本身)。然后通过v1的项迭代将得到内部字典的每个键和值。现在您可以检查某个键是否有某个值,并执行您想要的操作。

相关内容

  • 没有找到相关文章

最新更新