首页 > 解决方案 > 如何在python中拆分这种类型的字典

问题描述

我已经使用烧瓶创建了 Web 服务,因此添加了请求 JSON 参数,但现在问题是如何将我的 dict 拆分为简单数据

我的字典是

order={
   "userid":17,
   "details":[
      {
         "productid":1,
         "eachprice":45,
         "quantity":1,
         "price":45
      },
      {
         "productid":3,
         "eachprice":749,
         "quantity":1,
         "price":749
      }
   ]
}

所以我分裂喜欢

for x, y in order.items():
            print(x, y)

但问题是我如何打印嵌套数据

标签: pythonjson

解决方案


一个快速但不太好(=不是一般)的解决方案是:

for x, y in order.items():
    print(x,y, type(y))
    if type(y) == list:                     # check if the value is a list
        for element in y:                   # loop lists
            for k, v in element.items():    # loop dictionaries within the list
                print(k,v)

推荐阅读