получить первый элемент из словаря, который является массивом - python - PullRequest
0 голосов
/ 24 марта 2020

У меня есть информация заголовка хранилища массива:

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

спасибо

1 Ответ

2 голосов
/ 24 марта 2020

Я думаю, что было бы безопаснее использовать словарные ключи, например, так:

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

Таким образом, вы не полагаетесь на порядок внутри dict (dict не упорядочен)

EDIT : Только что увидел ваши изменения и то, что вы ожидаете получить, вот простой способ получить их:

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...