【问题标题】:get first element from dictionary which is an array - python从字典中获取第一个元素,它是一个数组 - python
【发布时间】:2020-03-24 11:50:37
【问题描述】:

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

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

谢谢

【问题讨论】:

  • 标题中根本没有数组,所以没有first元素的办法。请说明您期望的价值
  • dicts 是无序的。没有“第一”。为什么不能使用它的键索引它?
  • 我要获取值:已定义
  • ...所以使用"defined" 作为您的密钥。 elem["defined"],不是elem[0]
  • 但我希望它以我为所有其他标题定义的方式

标签: python http-headers


【解决方案1】:

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

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

【讨论】:

  • 一个简单的问题,我怎样才能只打印每个标题的“定义”值?
  • 只需替换打印语句中的内容
猜你喜欢
  • 2012-12-08
  • 2018-12-31
  • 1970-01-01
  • 2013-06-21
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-10
  • 2010-12-27
相关资源
最近更新 更多