【问题标题】:converting dictionary within a list to JSON format using python使用python将列表中的字典转换为JSON格式
【发布时间】:2020-09-09 20:18:17
【问题描述】:

我在下面的列表中有一本字典

b = [
    {
        "ServiceLevel": {
            "S": "AA"
        },
        "ReadyTime": {
            "S": "2020-01-31T12:00:00"
        },
        "DeliveryDate": {
            "S": "2020-02-15T12:00:00"
        }
    }
]

我正在尝试访问该内部字典中的元素并将它们转换为 JSON 格式: 我的尝试:

a = b[0]
for key, value in sorted(a.items()):
    a1 = print(key, value)

for i in a1:
    b1 = a1[i]
    print(b1)

我正在尝试得到这个输出:

b = {   
        "ServiceLevel": "AA",
        "ReadyTime": "2020-01-31T12:00:00",
        "ReadyDate": "2020-01-31T12:00:00",    
}

错误:TypeError:“NoneType”对象不可调用

【问题讨论】:

  • 您使用的是哪个 Python 版本?该错误消息看起来不对。
  • python 3.7 @ 超级雨
  • 嗯,我刚刚尝试了 3.7.8 并按预期得到了“...不可迭代”。

标签: python python-3.x list dictionary tuples


【解决方案1】:

您正在将 print() 方法分配给变量,这是 NoneType 错误

a1 = print(key, value) # variable a1 is NoneType
for i in a1: # error because variable a1 is not iterable

使用:

b1 = {}
for key, value in b[0].items():
    b1[key] = value['S']
print(b1)

【讨论】:

  • 我是 python 编程的初学者,我不知道如何使用 values['S']。我将它存储在 print 中,并认为我可以迭代该 print 语句中的元素。我试过你的答案,它按预期工作。谢谢
猜你喜欢
  • 2023-03-10
  • 2014-02-26
  • 2017-07-02
  • 1970-01-01
  • 2013-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-10
  • 2015-07-23
相关资源
最近更新 更多