【问题标题】:Unexpected Output When Iterating Over List of Dictionaries - Python & Microsoft Graph API迭代字典列表时出现意外输出 - Python 和 Microsoft Graph API
【发布时间】:2019-02-25 04:35:07
【问题描述】:

我正在尝试从从 Microsoft Graph 提取的 JSON 文件中迭代字典列表。我正在使用的代码能够将列表存储在一个变量中,但我得到的不是预期的 9 个项目,而是 27 个。

我的代码是:

for i in range(len(json_data_list)):
    try:
        for key in json_data_list[i]:
            headers.append(json_data_list[i]['internetMessageHeaders'])
    except KeyError:
        continue
    i += 1

以下是 JSON 数据的示例:

{
"@odata.context": "https://graph.microsoft.com/beta/$metadata#users('48d31887-5fad-4d73-a9f5-3c356e68a038')/messages(internetMessageHeaders)",
"@odata.nextLink": "https://graph.microsoft.com/beta/me/messages?$select=internetMessageHeaders&$skip=12",
"value": [
    {
        "@odata.etag": "W/\"CQAAABYAAAAiIsqMbYjsT5e/T7KzowPTAAEMTBu8\"",
        "id": "AAMkAGVmMDEzMTM4LTZmYWUtNDdkNC1hMDZiLTU1OGY5OTZhYmY4OABGAAAAAAAiQ8W967B7TKBjgx9rVEURBwAiIsqMbYjsT5e-T7KzowPTAAAAAAEMAAAiIsqMbYjsT5e-T7KzowPTAAEMOXaXAAA="
    },
    {
        "@odata.etag": "W/\"CQAAABYAAAAiIsqMbYjsT5e/T7KzowPTAAEMTBuN\"",
        "id": "AAMkAGVmMDEzMTM4LTZmYWUtNDdkNC1hMDZiLTU1OGY5OTZhYmY4OABGAAAAAAAiQ8W967B7TKBjgx9rVEURBwAiIsqMbYjsT5e-T7KzowPTAAAAAAEMAAAiIsqMbYjsT5e-T7KzowPTAAEMOXaWAAA=",
        "internetMessageHeaders": [
            {
                "name": "Received",
                "value": "from DM6PR15MB2425.namprd15.prod.outlook.com (2603:10b6:102:2::22) by BYAPR15MB2423.namprd15.prod.outlook.com with HTTPS via CO2PR05CA0054.NAMPRD05.PROD.OUTLOOK.COM; Mon, 10 Sep 2018 21:52:40 +0000"
            },
            {
                "name": "Received",
                "value": "from CO1PR15CA0057.namprd15.prod.outlook.com (2603:10b6:101:1f::25) by DM6PR15MB2425.namprd15.prod.outlook.com (2603:10b6:5:8e::11) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.1122.19; Mon, 10 Sep 2018 21:52:38 +0000"
            },

【问题讨论】:

  • 您是如何获得 JSON 的?您是否使用它开始使用 Microsoft Graph 和 Python? developer.microsoft.com/en-us/graph/get-started/python
  • 是的,我使用快速入门指南创建了应用程序,并且正在解析从 Graph Explorer 获得的本地存储的 JSON 文件。

标签: python rest dictionary microsoft-graph-api


【解决方案1】:

意识到我不需要第二个 for 循环。

这按预期工作:

for i in range(len(jsonDataList)):
    try:
        headers.append(jsonDataList[i]['internetMessageHeaders'])
    except KeyError:
        continue
    i += 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多