Search code examples
pythonpython-3.xdictionarylambdalist-comprehension

for loops reduction to list comprehension or use of lambda function


categories = [
  {
    "CategoryUId": "f34cc7a8-ac38-4f1f-a637-08bd034d74f3",
    "SubCategory": [
      {
        "SubCategoryUId": "9b37dbf3-4b4d-4bbb-8bc4-2ce036b69042"
      },
      {
        "SubCategoryUId": "d4131c98-9823-4354-b587-c736cd77df4d"
      }
    ]
  },
  {
    "CategoryUId": "460366f6-c8ef-4e4e-80a7-4ace9c59122c",
    "SubCategory": [
      {
        "SubCategoryUId": "ed6dbfb9-bc1a-4161-b040-f9aba55c995a"
      },
      {
        "SubCategoryUId": "06246a88-fe8a-42fa-aba6-3393af463397"
      },
      {
        "SubCategoryUId": "2f37fd26-fae5-4dc4-9f10-4e87a2f5ae68"
      }
    ]
  }
]

A basic example where is categories is a list of dictionaries.

for item in categories:
    categoryUId = item['CategoryUId']
    for value in item['SubCategory']:
        subcategory = value['SubCategoryUId']
        subcategoryList.append(subcategory)
    dict = {categoryUId : subcategoryList}

I am going through some random python exercises, is it possible to use lambda function or the List comprehension for the above mentioned code snippet.

Please assist me with an approach.


Solution

  • It seems this is the outcome you expected:

    out = {d['CategoryUId']: [v['SubCategoryUId'] for v in d['SubCategory']] for d in categories}
    

    The above code with a lambda in map (extremely ugly though; do not recommend):

    out = dict(map(lambda d: (d['CategoryUId'], [*map(lambda v:v['SubCategoryUId'], d['SubCategory'])]), categories))
    

    Output:

    {'f34cc7a8-ac38-4f1f-a637-08bd034d74f3': ['9b37dbf3-4b4d-4bbb-8bc4-2ce036b69042',
      'd4131c98-9823-4354-b587-c736cd77df4d'],
     '460366f6-c8ef-4e4e-80a7-4ace9c59122c': ['ed6dbfb9-bc1a-4161-b040-f9aba55c995a',
      '06246a88-fe8a-42fa-aba6-3393af463397',
      '2f37fd26-fae5-4dc4-9f10-4e87a2f5ae68']}