Outcast
Outcast

Reputation: 5117

Apply function per group of values of a key in list of dicts

Let's suppose I have this:

my_list = [{'id':'1','value':'1'},
{'id':'1','value':'8'},
{'id':'2','value':'2'},
{'id':'2','value':'3'},
{'id':'2','value':'5'},
]

and I want to apply a function (eg shuffle) for each group of values separately for the key id.

So I would like to have this for example:

my_list = [{'id':'1','value':'1'},
{'id':'1','value':'8'},
{'id':'2','value':'3'},
{'id':'2','value':'5'},
{'id':'2','value':'2'},
]

Therefore I do not want something to change between the different groups of values (eg id=1,2 etc) but only within each one separately.

Upvotes: 0

Views: 40

Answers (1)

Austin
Austin

Reputation: 26039

Use groupby directly in case your list is sorted by 'id' or sort by 'id' and use groupby:

from itertools import groupby
import random

my_list = [{'id':'1','value':'1'},
           {'id':'1','value':'8'},
           {'id':'2','value':'2'},
           {'id':'2','value':'3'},
           {'id':'2','value':'5'}]

res = []
for k, g in groupby(my_list, lambda x: x['id']):
    lst = list(g)
    random.shuffle(lst)
    res += lst

print(res)
# [{'id':'1','value':'1'},
#  {'id':'1','value':'8'},
#  {'id':'2','value':'3'},
#  {'id':'2','value':'5'},
#  {'id':'2','value':'2'}]

Upvotes: 2

Related Questions