[英]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.