简体   繁体   中英

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]

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]})
print(result)

output

defaultdict(<class 'list'>, {'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}]})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM