【问题标题】:How to get specific data from a dictionary in python如何从python中的字典中获取特定数据
【发布时间】:2019-11-03 03:15:57
【问题描述】:

所以我有一个 json 文件。我在 python 中将它作为 json 文件加载并尝试从字典中获取项目。我可以访问“作者”的“sha”并获取其所有组件,但我如何才能仅访问“消息”、“名称”和“日期”?

我尝试使用此代码访问“消息”,但出现关键错误:

    data = json.load(json_file)
    print(str(type(data))) # class <dict>
    for p in data['commits']:
        print(p['message'])

我的文件看起来像这样:(它包含多个提交消息):

{

   "commits":[  
      {  
         "sha":"exampleSHA",
         "node_id":"exampleID",
         "commit":{  
            "author":{  
               "name":"example",
               "email":"example@example.se",
               "date":"2015-09-07T22:06:51Z"
            },
            "committer":{  
               "name":"example",
               "email":"example@example.se",
               "date":"2015-09-07T22:06:51Z"
            },
            "message":"Added LaTex template and instructions",
            "tree":{  
               "sha":"examplesha",
               "url":"http://example.url"
            },
         "parents":[]
      }}
   ]
}

我想从字典中获取很多“消息”。

结果是这样的:

AuthorName   Message                                Date
example      Added LaTex template and instructions  2013-07-08T20:16:51Z
example2     Message2                               2015-09-07T22:06:51Z
....         ....                                   .....

【问题讨论】:

    标签: python file extract


    【解决方案1】:

    试试这个:

    data = json.load(json_file)
    print(str(type(data))) # class <dict>
    for p in data['commits']:
        print(p['commit']['message'])
    

    message 字段嵌套在 commit 字段中。

    【讨论】:

    • 是的,行得通!谢谢:我会在 10 分钟后接受答案
    猜你喜欢
    • 1970-01-01
    • 2021-06-29
    • 1970-01-01
    • 2016-11-20
    • 1970-01-01
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多