Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group list of dictionaries python

How can i group similar keys of a dictionary in a list

if i have

data = [{'quantity': 2, 'type': 'Vip'}, {'quantity': 23, 'type': 'Vip'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}, {'quantity': 2, 'type': 'Regular'}]

and i want it to output like this

res = {'Regular': [{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'}], 'Vip': [{'quantity': 23, 'type': 'Vip'},{'quantity': 23, 'type': 'Vip'}]}

Here is the code i have tried but it gives me double of the key probably because of the loop

 res = defaultdict(list)
 for i in data:
    if len(res) >= 1:
       for q in res:
          if q == i['type']:
            res[q].append(i)
            break
          else:
            res[i['type']].append(i)
            break
  res[i['type']].append(i)
like image 737
Shags mando Avatar asked Dec 22 '25 14:12

Shags mando


1 Answers

I think yo dou not fully understand the idea of a defaultdict. A defaultdict will produce a new object if none exists at lookup.

So you can simply use:

from collections import defaultdict

res = defaultdict(list)

for i in data:
    res[i['type']].append(i)

which yields:

>>> pprint(res)
defaultdict(<class 'list'>,
            {'Regular': [{'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'},
                         {'quantity': 2, 'type': 'Regular'}],
             'Vip': [{'quantity': 2, 'type': 'Vip'},
                     {'quantity': 23, 'type': 'Vip'}]})

(pprint is pretty print, but does not change the content).

Note that here we copy there reference to the dictionary to the new list, so we do not create a new dictionary. Furthermore the result is a defaultdict. We can cast it to a vanilla dictionary with dict(res).

like image 182
Willem Van Onsem Avatar answered Dec 24 '25 03:12

Willem Van Onsem