I have a list that contains a different dictionaries;
[{'header-name': 'x-frame-options', 'ignore': False, 'expected-value': ['deny', 'sameorigin']}, {'header-name': 'content-security-policy', 'ignore': False, 'expected-value': []}]
I'm using this method, to extract all the fields from dictionary
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}
my goal is get header-name content and ignore content and expected-value content?
The second if-statement is never going to be true, because it is nested within the first one. That means it is only evaluated if the outer one is True. Same goes for the first one. Think about it:
The first if-statement checks if keys
is equal to "header-name"
and the second one checks if again keys
is equal to "ignore"
. Of course if it has the value "header-name"
it won't also be "ignore"
.
You need to un-nest our if-statements:
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)
EDIT: You need to separate your concerns a bit. One part of the logic (the one I have provided here) is just for determining which key you're looking at. You can then go on to do stuff with the values they contain:
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)
Notice how I stored the value of "ignore"
, and then the next time the loop went around I used that stored value to determine if I'll print "expected-value"
.
By the way, this whole structure is a bit strange. If the keys of the dictionaries are known, why not use them directly:
if value["header-name"] == "x-frame-options":
if value["ignore"] == False:
print(value["expected-value"]) # Do your stuff here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.