首页 > 解决方案 > 从字典中获取第一个元素,它是一个数组 - python

问题描述

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

{'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;
....

谢谢

标签: pythonhttp-headers

解决方案


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

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

这样你就不用依赖 dict 里面的排序了(dict没有排序)

编辑:刚刚看到你的编辑和你期望的输出,这里有一个简单的方法:

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

推荐阅读