Search code examples
python-3.xlistdictionarylist-comprehensiondictionary-comprehension

nest dictionary list to another dictionary list based on key using comprehension list


I'm trying to use comprehension list to nest one dictionary list to another list of dictionary, I have two dictionary lists one is categories and another is oils. Add the result of list oils to each category if oils category_id is equal category id.

def nest(parent, child):
    items = []
    for element in child:
        if element.get('category_id') == parent.get('id'):
            items.append(element)
        parent.update({'items': items})
    return parent

def merge(parent, child):
    results = []
    for element in parent:
        results.append(nest(element, child))
    return results


categories = [
    {'id': 1000, 'name': 'Single'},
    {'id': 2000, 'name': 'Blend'}]

oils = [
    {'id': 100, 'name': 'Orange', 'category_id': 1000},
    {'id': 101, 'name': 'Lavender', 'category_id': 1000},
    {'id': 102, 'name': 'Peppermint', 'category_id': 1000},
    {'id': 104, 'name': 'Inspired', 'category_id': 2000},
    {'id': 105, 'name': 'Focus', 'category_id': 2000},
    {'id': 107, 'name': 'Tea Tree', 'category_id': 1000}]

results = merge(categories, oils)

print(results)
# output:
# [
#     {'id': 1000, 'name': 'Single', 'items': [
#         {'id': 100, 'name': 'Orange', 'category_id': 1000}, 
#         {'id': 101, 'name': 'Lavender', 'category_id': 1000}, 
#         {'id': 102, 'name': 'Peppermint', 'category_id': 1000}, 
#         {'id': 107, 'name': 'Tea Tree', 'category_id': 1000}
#     ]}, 
#     {'id': 2000, 'name': 'Blend', 'items': [
#         {'id': 104, 'name': 'Inspired', 'category_id': 2000}, 
#         {'id': 105, 'name': 'Focus', 'category_id': 2000}
#     ]}
# ]

I'm trying to convert the above to comprehension list without success

merged = [
    element.update({'items': nest}) for nest in oils
    for element in categories if element.get('id') == nest.get('category_id')
]

print(merged)
# output: [None, None, None, None, None, None]

Solution

  • merged = [dict(**c, items=[o for o in oils if o['category_id'] == c['id']]) for c in categories]
    
    from pprint import pprint
    pprint(merged)
    

    Prints:

    [{'id': 1000,
      'items': [{'category_id': 1000, 'id': 100, 'name': 'Orange'},
                {'category_id': 1000, 'id': 101, 'name': 'Lavender'},
                {'category_id': 1000, 'id': 102, 'name': 'Peppermint'},
                {'category_id': 1000, 'id': 107, 'name': 'Tea Tree'}],
      'name': 'Single'},
     {'id': 2000,
      'items': [{'category_id': 2000, 'id': 104, 'name': 'Inspired'},
                {'category_id': 2000, 'id': 105, 'name': 'Focus'}],
      'name': 'Blend'}]
    

    EDIT (to add dynamic variable):

    variable = 'elements' # this is your dynamic variable
    merged = [dict(**c, **{variable: [o for o in oils if o['category_id'] == c['id']]}) for c in categories]