algorithm - Python: group list items in a dict -


i want generate dictionary list of dictionaries, grouping list items value of key, such as:

input_list = [         {'a':'tata', 'b': 'foo'},         {'a':'pipo', 'b': 'titi'},         {'a':'pipo', 'b': 'toto'},         {'a':'tata', 'b': 'bar'} ] output_dict = {         'pipo': [              {'a': 'pipo', 'b': 'titi'},               {'a': 'pipo', 'b': 'toto'}          ],          'tata': [              {'a': 'tata', 'b': 'foo'},              {'a': 'tata', 'b': 'bar'}          ] } 

so far i've found 2 ways of doing this. first iterates on list, create sublists in dict each key value , append elements matching these keys sublist :

l = [      {'a':'tata', 'b': 'foo'},     {'a':'pipo', 'b': 'titi'},     {'a':'pipo', 'b': 'toto'},     {'a':'tata', 'b': 'bar'}     ]  res = {}  e in l:     res[e['a']] = res.get(e['a'], [])      res[e['a']].append(e) 

and using itertools.groupby:

import itertools operator import itemgetter  l = [          {'a':'tata', 'b': 'foo'},         {'a':'pipo', 'b': 'titi'},         {'a':'pipo', 'b': 'toto'},         {'a':'tata', 'b': 'bar'} ]  l = sorted(l, key=itemgetter('a')) res = dict((k, list(g)) k, g in itertools.groupby(l, key=itemgetter('a'))) 

i wonder alternative efficient ?

is there more pythonic/concise or better performing way of achieving ?

is correct want group input list value of 'a' key of list elements? if so, first approach best, 1 minor improvement, use dict.setdefault:

res = {} item in l:     res.setdefault(item['a'], []).append(item) 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -