Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: group list items in a dict

Tags:

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 ?

like image 923
Erwan Queffélec Avatar asked Jun 26 '15 11:06

Erwan Queffélec


People also ask

Can a dict contain a list?

A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

How do you group dictionary using keys?

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().


1 Answers

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) 
like image 174
Bernhard Avatar answered Sep 24 '22 03:09

Bernhard