python - 从字典中获取第一个元素,它是一个数组 - 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;
....
谢谢
解决方案
我认为像这样使用字典键会更安全
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
推荐阅读
- javascript - React 和 onClick 在 div 或 span 中以及可能的缺点
- javascript - 找不到路线
- maven - 如何在使用 native-maven 插件创建 JNI .so 后运行 JUnit 测试
- git - 将项目分支合并到演示分支的正确程序
- html - Bootstrap 4:内联表单按钮高度
- excel - 如何使用 selenium+chrome+vba 在 trello 上单击板?
- c++ - 如何使用原语和 Eigen 创建尾随返回类型?
- javascript - 基于同一对象中另一个值的最大值/最小值的返回值
- here-api - 如何在一张地图上显示多个地址
- android - Android ViewPager ZoomOut 动画