Issue
lets suppose i have this queryset_array
:
queryset_array = [{"category":"a"},{"category":"a"},{"category:"b"},{"category":"b"},{"category":"c"},{"category":"c"}]
How can I convert this array using most efficient pythonic way into:
array_1 = [{"category":"a"},{"category":a"}}]
array_2 = [{"category":"b"},{"category":"b"}]
array_3 = [{"category":"c"},{"category":"c"}]
Solution
Try this:
from itertools import groupby
queryset_array = [{"category": "b"}, {"category": "a"}, {"category": "b"}, {"category": "b"}, {"category": "c"},
{"category": "d"}]
def key_func(k):
return k['category']
sorted_data = sorted(queryset_array, key=key_func)
count = 1
for key, value in groupby(sorted_data , key_func):
print(f'array_{count}= {list(value)}')
count += 1
Output
array_1= [{'category': 'a'}]
array_2= [{'category': 'b'}, {'category': 'b'}, {'category': 'b'}]
array_3= [{'category': 'c'}]
array_4= [{'category': 'd'}]
Answered By - Dev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.