【问题标题】:print int value from python nested dictionary, 'int' object is not iterable从python嵌套字典打印int值,'int'对象不可迭代
【发布时间】:2018-03-19 13:08:38
【问题描述】:

我尝试访问嵌套的 JSON 文件并通过将其导入 python 字典来打印其数据。当我将它们打印出来时,最后一个值出现错误,它是字典中的 int 值。

这是我的 JSON 数据

{
"time": {
    "Thursday": {
        "21:00": 4,
        "1:00": 1,
        "4:00": 1,
        "2:00": 1,
        "20:00": 2,
        "22:00": 1,
        "19:00": 1,
        "15:00": 2,
        "13:00": 1,
        "23:00": 2
    },
    "Wednesday": {
        "11:00": 2,
        "13:00": 2,
        "14:00": 1,
        "17:00": 1,
        "6:00": 1,
        "2:00": 1,
        "0:00": 2,
        "1:00": 1,
        "21:00": 1,
        "18:00": 1,
        "19:00": 1,
        "20:00": 2
    },
    "Sunday": {
        "18:00": 1,
        "16:00": 1,
        "14:00": 1,
        "19:00": 2,
        "17:00": 1,
        "23:00": 1,
        "21:00": 1,
        "20:00": 5,
        "6:00": 1,
        "0:00": 1,
        "2:00": 2,
        "3:00": 3
    },
    "Friday": {
        "16:00": 1,
        "14:00": 2,
        "10:00": 2,
        "23:00": 1,
        "19:00": 2,
        "18:00": 1,
        "15:00": 1,
        "21:00": 2,
        "22:00": 2,
        "3:00": 1,
        "0:00": 2
    },
    "Saturday": {
        "21:00": 1,
        "23:00": 3,
        "18:00": 4,
        "10:00": 1,
        "12:00": 1,
        "13:00": 3,
        "14:00": 1,
        "15:00": 1,
        "16:00": 2,
        "17:00": 3,
        "2:00": 1,
        "0:00": 1,
        "1:00": 2
    },
    "Monday": {
        "12:00": 1,
        "11:00": 1,
        "14:00": 1,
        "18:00": 1,
        "19:00": 1,
        "23:00": 1,
        "20:00": 1
    },
    "Tuesday": {
        "18:00": 2,
        "12:00": 1,
        "13:00": 2,
        "16:00": 1,
        "15:00": 1,
        "4:00": 1,
        "21:00": 1,
        "20:00": 2,
        "23:00": 2
    }
},
"business_id": "7KPBkxAOEtb3QeIL9PEErg"

}

这是我的python代码:

import json
with open('dataset/sample-checkin.json') as json_data:
    d = json.load(json_data)

for day in d["time"]:
    for time in d["time"][day]:
        for checkin in d["time"][day][time]:
            print(day, time, checkin)

错误:签入 d["time"][day][time]: TypeError: 'int' object is not iterable

【问题讨论】:

    标签: python json dictionary


    【解决方案1】:

    最后一个循环没有意义......那里没有什么可以循环的。 (正如错误所说,值是int。)我想你可能想要这样的东西:

    for day in d["time"]:
        for time in d["time"][day]:
            checkin = d["time"][day][time]
            print(day, time, checkin)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-14
      • 2022-07-01
      • 1970-01-01
      • 2015-04-06
      • 2013-10-31
      • 2018-12-14
      • 2013-08-02
      相关资源
      最近更新 更多