首页 > 解决方案 > 遇到 Keyerror 0 的问题

问题描述

在“for k, v in entries[0].items():”行中出现错误“keyerror 0”。我的代码:

import requests
import json

session = requests.Session()
session.headers['User-Agent'] = (
    f'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) '
    f'AppleWebKit/537.36 (KHTML, like Gecko) '
    f'Chrome/34.0.1847.131 Safari/537.36'
)
api_url = 'https://api.hh.ru/vacancies'
response = session.get(api_url)
entries = json.loads(response.text)

# Let's check the first entry
for k, v in entries[0].items():
    print(f'{k}: {v}')

标签: pythonjsonapikeyerror

解决方案


您需要检查您的entriescontainsitems键,然后您可以访问第一项并打印其键和值:

if "items" in entries:
    for k, v in entries["items"][0].items():
        print(f'{k}: {v}')

输出:

id: 43908393
premium: False
name: Руководитель фирменного салона
department: None
has_test: False
response_letter_required: False
area: {'id': '80', 'name': 'Якутск', 'url': 'https://api.hh.ru/areas/80'}
salary: {'from': 40000, 'to': 80000, 'currency': 'RUR', 'gross': False}
type: {'id': 'open', 'name': 'Открытая'}
address: {'city': 'Якутск', 'street': 'улица Чернышевского', 'building': '74/8', 'description': None, 'lat': 62.005122, 'lng': 129.716206, 'raw': 'Якутск, улица Чернышевского, 74/8', 'metro': None, 'metro_stations': [], 'id': '2985691'}
response_url: None
sort_point_distance: None
published_at: 2021-04-16T03:36:19+0300
created_at: 2021-04-16T03:36:19+0300
archived: False
apply_alternate_url: https://hh.ru/applicant/vacancy_response?vacancyId=43908393
insider_interview: None
url: https://api.hh.ru/vacancies/43908393?host=hh.ru
alternate_url: https://hh.ru/vacancy/43908393
relations: []
employer: {'id': '3263696', 'name': 'Райтон (ИП Луковцев Георгий Егорович)', 'url': 'https://api.hh.ru/employers/3263696', 'alternate_url': 'https://hh.ru/employer/3263696', 'logo_urls': {'90': 'https://hhcdn.ru/employer-logo/2966436.png', '240': 'https://hhcdn.ru/employer-logo/2966437.png', 'original': 'https://hhcdn.ru/employer-logo-original/631321.png'}, 'vacancies_url': 'https://api.hh.ru/vacancies?employer_id=3263696', 'trusted': True}
snippet: {'requirement': 'Поспешите: нужно всего несколько человек, как только мы их наберем - найм мы закроем.', 'responsibility': 'Вы будете руководить салоном, обучать и контролировать работу своих подчиненных, помогая им повышать как свои продажи, так и, тем самым...'}
contacts: None
schedule: {'id': 'fullDay', 'name': 'Полный день'}
working_days: []
working_time_intervals: []
working_time_modes: []
accept_temporary: False

推荐阅读