Search code examples
pythonpython-3.xlistlist-comprehensiondictionary-comprehension

How to append a list in list comprehension


I have data like data = [('101339602', 's', 6), ('101339602', 'm', 7), ('101339602', 'xl', 3), ('101339602', 'l', 3), ('109302806', 'm', 4)]

Now, I want to show grouped data(based on id) like below using list comprehension

[
    {
        '101339602': [{ 'size_worn': 's', 'total': 6}, { 'size_worn': 'm', 'total': 7}, { 'size_worn': 'xl', 'total': 3}, { 'size_worn': 'l', 'total': 3}]
    },
    {
        '109302806': [{'size_worn': 'm', 'total': 4}]
    }
]

I've written following code but don't know how to append data if id is same

[{x[0]: [{"size_worn": x[1], "total": x[2]}]}
  for x in _request_initialized_per_size_no_chart]

Solution

  • Something like the below

    from collections import defaultdict
    data = [('101339602', 's', 6), ('101339602', 'm', 7), ('101339602', 'xl', 3), ('101339602', 'l', 3), ('109302806', 'm', 4)]
    
    result = defaultdict(list)
    for d in data:
      result[d[0]].append({'size_worn':d[1],'total':d[2]})
    result = [{k:v} for k,v in result.items()]
    print(result)
    

    output

    [{'101339602': [{'size_worn': 's', 'total': 6}, {'size_worn': 'm', 'total': 7}, {'size_worn': 'xl', 'total': 3}, {'size_worn': 'l', 'total': 3}]}, {'109302806': [{'size_worn': 'm', 'total': 4}]}]