从作为数组的字典中获取第一个元素-python

问题描述 投票:-1回答:1

我有一个数组存储头信息:

{'x-frame-options': {'defined': True, 'warn': 0, 'contents': 'SAMEORIGIN'}, 'strict-transport-security': {'defined': True, 'warn': 0, 'contents': 'max-age=15552000'}, 'access-control-allow-origin': {'defined': False, 'warn': 1, 'contents': ''}, 'content-security-policy': {'defined': True, 'warn': 0, 'contents': "upgrade-insecure-requests; frame-ancestors 'self' https://stackexchange.com"}, 'x-xss-protection': {'defined': False, 'warn': 1, 'contents': ''}, 'x-content-type-options': {'defined': False, 'warn': 1, 'contents': ''}}

我想获得字典的第一个元素

#header is a return array that store all header information,

headers = headersecurity.verify_header_existance(url, 0)
for header in headers:
    if header.find("x-frame-options"):
        for headerSett in header:
            defined = [elem[0] for elem in headerSett.values()] # here I don't get first element
            print(defined)

预期结果是:

x-frame-options : defined = True;
access-control-allow-origin : defined = True;
x-content-type-options : defined = True;
....

谢谢

python http-headers
1个回答
2
投票

我认为像这样使用字典键会更安全

headers['x-frame-options']['defined']

这样,您就不必依赖于字典内部的排序(字典没有排序)

编辑:刚看到您的编辑以及您期望的输出,这是获得它的一种简单方法:

for key, value in headers.items():
    if "defined" in value:
        print(f"{key} : defined = {value['defined']}")

输出:

x-frame-options : defined = True
strict-transport-security : defined = True
access-control-allow-origin : defined = False
content-security-policy : defined = True
x-xss-protection : defined = False
x-content-type-options : defined = False
© www.soinside.com 2019 - 2024. All rights reserved.