I want to generate a dictionary from a list of dictionaries, grouping list items by the value of some 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 two ways of doing this. The first simply iterates over the list, create sublists in the dict for each key value and append elements matching these keys to the sublist :
l = [ {'a':'tata', 'b': 'foo'}, {'a':'pipo', 'b': 'titi'}, {'a':'pipo', 'b': 'toto'}, {'a':'tata', 'b': 'bar'} ] res = {} for e in l: res[e['a']] = res.get(e['a'], []) res[e['a']].append(e)
And another using itertools.groupby
:
import itertools from 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)) for k, g in itertools.groupby(l, key=itemgetter('a')))
I wonder which alternative is the most efficient ?
Is there any more pythonic/concise or better performing way of achieving this ?
A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.
Method : Using sorted() + items() + defaultdict() The defaultdict() is used to create a dictionary initialized with lists, items() gets the key-value pair and grouping is helped by sorted().
Is it correct that you want to group your input list by the value of the 'a' key of the list elements? If so, your first approach is the best, one minor improvement, use dict.setdefault
:
res = {} for item in l: res.setdefault(item['a'], []).append(item)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With