如何在python中拆分这种类型的字典

2024-09-19 23:28:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经使用flask创建了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)

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


Tags: 数据webjsonflaskfor参数字典order
2条回答

一个快速且不太好的解决方案是:

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)

基于递归计算对象大小的方法,此递归解决方案基本上将整个数据结构展平为一维列表:

import itertools
def unpack(object, lst=[]):
    typ = type(object)
    dict_handler = lambda d: itertools.chain.from_iterable(d.items())

    if typ is dict:
        object = dict_handler(object)       # Iterate over both keys and values when dict
    if typ in [list, set, tuple, dict, frozenset]:
        for e in object:
            unpack(e, lst)                  # Recursive call for elements in container
    else:
        lst.append(object)
    return lst
    
print(unpack(data))

相关问题 更多 >