[英]how to get dictionary items stored in a list in python 3.6
我有一个包含不同词典的列表;
[{'header-name': 'x-frame-options', 'ignore': False, 'expected-value': ['deny', 'sameorigin']}, {'header-name': 'content-security-policy', 'ignore': False, 'expected-value': []}]
我正在使用这种方法,从字典中提取所有字段
def use_custom_setting(self, header, contents):
warn = 1
if header == "x-frame-options":
for value in self.custom:
for keys, values in value.items():
if keys == "header-name" and values == "x-frame-options":
print(keys,values)
if keys== "ignore" and values == False: # i dont reach here
if keys == "expected-value":
print(values)
if contents.lower() in values:
warn = 0
else:
warn = 1
print(values)
else:
print("This header is skipped based on configure file")
return {'defined': True, 'warn': warn, 'contents': contents}
我的目标是获取标题名称内容并忽略内容和预期值内容?
第二个 if 语句永远不会为真,因为它嵌套在第一个语句中。 这意味着只有在外部为 True 时才会对其进行评估。 第一个也一样。 想想看:
第一个 if 语句检查keys
是否等于"header-name"
,第二个检查keys
是否再次等于"ignore"
。 当然,如果它具有"header-name"
值,它也不会是"ignore"
。
您需要取消嵌套我们的 if 语句:
for keys, values in value.items():
if keys == "header-name" and values == "x-frame-options":
print(keys,values)
if keys== "ignore" and values == False: # i dont reach here
print(keys,values)
if keys == "expected-value":
print(keys,values)
编辑:您需要将您的担忧分开一点。 逻辑的一部分(我在此处提供的部分)仅用于确定您正在查看哪个键。 然后,您可以继续使用它们包含的值执行操作:
ignoreItem = False # This variable is reset for every dictionary
for keys, values in value.items():
if keys== "ignore": # i dont reach here
ignoreItem = values
if keys == "expected-value" and ignoreItem:
print(keys,values)
请注意我如何存储"ignore"
的值,然后下一次循环时我使用该存储值来确定是否打印"expected-value"
。
顺便说一下,这整个结构有点奇怪。 如果字典的键是已知的,为什么不直接使用它们:
if value["header-name"] == "x-frame-options":
if value["ignore"] == False:
print(value["expected-value"]) # Do your stuff here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.