从嵌套数据中提取Python列表理解

2024-05-23 22:23:03 发布

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

我是python新手,正在尝试提取一些嵌套数据

下面是两个产品的JSON。产品可以属于零个或多个类别

 {  
   "Item":[  
      {   
         "ID":"170",
         "InventoryID":"170",
         "Categories":[  
            {  
               "Category":[  
                  {  
                    "CategoryID":"444",
                    "Priority":"0",
                    "CategoryName":"Paper Mache"
                  },
                  {  
                     "CategoryID":"479",
                     "Priority":"0",
                     "CategoryName":"Paper Mache"
                  },
                  {  
                     "CategoryID":"515",
                     "Priority":"0",
                     "CategoryName":"Paper Mache"
                  }
               ]
            }
         ],
         "Description":"Approximately 9cm wide x 4cm deep.",
         "SKU":"111931"
      },
      {  
         "ID":"174",
         "InventoryID":"174",
     "    Categories":[  
            {  
                "Category":{  
                  "CategoryID":"888",
                  "Priority":"0",
                  "CategoryName":"Plaster"
                }
            }
         ],
         "Description":"Plaster Mould - Australian Animals",
         "SKU":"110546"
      }
   ],
   "CurrentTime":"2016-08-22 11:52:27",
   "Ack":"Success"
}

我想弄清楚一个产品属于哪一类。你知道吗

我提取的代码是如下所示:你知道吗

        for x in products: 
            productsInCategory = []
            for y in x['Categories']:
                for z in y['Category']:
                    if z['CategoryID'] == categories[i]['CategoryID']:
                        productsInCategory.append(x)

这个问题是,在这种情况下,第二个项目只包含一个类别,而不是一个类别数组,所以这一行

for z in y['Category']:

循环遍历类别而不是类别数组的属性,从而导致代码失败

我怎样才能避免这种情况?用列表理解语法能写得更优雅些吗?你知道吗


Tags: inidfor产品description类别papercategories
2条回答

在这种情况下,这是一个非常糟糕的文档结构;您不必处理这个问题。如果一个项目可以包含多个值,那么它应该始终是一个列表。你知道吗

尽管如此,您仍然可以在代码中通过检查它是否是列表来处理它。你知道吗

for x in products: 
    productsInCategory = []
    for y in x['Categories']:
        category = y['Category']
        if isinstance(category, dict):
            category = [category]
        for z in category:
            ...

(您可能需要考虑通常使用更具描述性的变量名;xyz对阅读代码的人没有很大帮助。)

我以前在JSON结构中经常遇到这个问题…频繁到几周前我为它编写了一个小库。。。你知道吗

nested key retriever (nkr)

试试发电机,看看它是否能解决你的问题。您应该能够简单地:

for x in products: 
    if product_id_searching_for in list(nkr.find_nested_key_values(x, 'CategoryID')):
         productsInCategory.append(x)

相关问题 更多 >