title: Python List Comprehension - extracting from nested data
body: <p>I'm new to Python and was trying to extract out some nested data.</p>
  <p>Here is the JSON for two products.  A product can belong to zero or more categories</p>
  <pre><code> {  
     &quot;Item&quot;:[  
        {   
           &quot;ID&quot;:&quot;170&quot;,
           &quot;InventoryID&quot;:&quot;170&quot;,
           &quot;Categories&quot;:[  
              {  
                 &quot;Category&quot;:[  
                    {  
                      &quot;CategoryID&quot;:&quot;444&quot;,
                      &quot;Priority&quot;:&quot;0&quot;,
                      &quot;CategoryName&quot;:&quot;Paper Mache&quot;
                    },
                    {  
                       &quot;CategoryID&quot;:&quot;479&quot;,
                       &quot;Priority&quot;:&quot;0&quot;,
                       &quot;CategoryName&quot;:&quot;Paper Mache&quot;
                    },
                    {  
                       &quot;CategoryID&quot;:&quot;515&quot;,
                       &quot;Priority&quot;:&quot;0&quot;,
                       &quot;CategoryName&quot;:&quot;Paper Mache&quot;
                    }
                 ]
              }
           ],
           &quot;Description&quot;:&quot;Approximately 9cm wide x 4cm deep.&quot;,
           &quot;SKU&quot;:&quot;111931&quot;
        },
        {  
           &quot;ID&quot;:&quot;174&quot;,
           &quot;InventoryID&quot;:&quot;174&quot;,
       &quot;    Categories&quot;:[  
              {  
                  &quot;Category&quot;:{  
                    &quot;CategoryID&quot;:&quot;888&quot;,
                    &quot;Priority&quot;:&quot;0&quot;,
                    &quot;CategoryName&quot;:&quot;Plaster&quot;
                  }
              }
           ],
           &quot;Description&quot;:&quot;Plaster Mould - Australian Animals&quot;,
           &quot;SKU&quot;:&quot;110546&quot;
        }
     ],
     &quot;CurrentTime&quot;:&quot;2016-08-22 11:52:27&quot;,
     &quot;Ack&quot;:&quot;Success&quot;
  }
  </code></pre>
  <p>I want to work out which Categories a product belongs to.</p>
  <p>My code for extraction is as follows:-</p>
  <pre><code>        for x in products: 
              productsInCategory = []
              for y in x['Categories']:
                  for z in y['Category']:
                      if z['CategoryID'] == categories[i]['CategoryID']:
                          productsInCategory.append(x)
  </code></pre>
  <p>This issue is that in this case the second item only contains one Category, not an array of categories so this line</p>
  <pre><code>for z in y['Category']:
  </code></pre>
  <p>loops through the properties of a Category and not a Category array and hence causes my code to fail.</p>
  <p>How can I protect against this?  And can this be written more elegantly with list comprehension syntax?</p>