【问题标题】:How to parse answer from api to dict not list in python如何解析从api到dict的答案不在python中列出
【发布时间】:2020-03-12 22:37:56
【问题描述】:

我第一个月学习python,如果这是一个愚蠢的问题,抱歉)。

import requests
url='https://api.github.com/repositories?q=language:python&sort=stars'
r=requests.get(url)
print('status code:', r.status_code)
response_dict=r.json()
print(response_dict.keys())

但是 response_dict 变成列表而不是字典类型。我怎样才能得到字典? 试图制作response_dict=dict(r.json())。得到这个错误。 “字典更新序列元素 #0 的长度为 46;需要 2”谢谢您的帮助。

【问题讨论】:

  • 您希望该字典中的键是什么?
  • 请提供您希望用这个解析的 JSON
  • 你想做什么?将列表转换为字典有什么意义?请提供当前和预期的输出。

标签: python json dictionary parsing


【解决方案1】:

您的response_dictlist of 100 dict,您可以使用:

response_dict=r.json()[0] # if you want to access the frist dict
print(response_dict.keys())

输出:

dict_keys(['id', 'node_id', 'name', 'full_name', 'private', 'owner', 'html_url', 'description', 'fork', 'url', 'forks_url', 'keys_url', 'collaborators_url', 'teams_url', 'hooks_url', 'issue_events_url', 'events_url', 'assignees_url', 'branches_url', 'tags_url', 'blobs_url', 'git_tags_url', 'git_refs_url', 'trees_url', 'statuses_url', 'languages_url', 'stargazers_url', 'contributors_url', 'subscribers_url', 'subscription_url', 'commits_url', 'git_commits_url', 'comments_url', 'issue_comment_url', 'contents_url', 'compare_url', 'merges_url', 'archive_url', 'downloads_url', 'issues_url', 'pulls_url', 'milestones_url', 'notifications_url', 'labels_url', 'releases_url', 'deployments_url'])

响应包含一个包含 100 个字典的列表

len(r.json())
# 100

【讨论】:

    【解决方案2】:

    您的回复是一个字典列表。如果你想提取单个项目,你可以说

    response_dict=r.json()[0]
    

    如果要将列表更改为字典,则可以使用每个项目的“id”参数作为键:

    response = r.json()
    response_dict = dict([ (i['id'], i) for i in response])
    

    或者如果您更喜欢使用“名称”参数:

    response_dict = dict([ (i['name'], i) for i in response ])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-03
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多