Shags mando
Shags mando

Reputation: 105

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)

Upvotes: 2

Views: 4130

Answers (2)

Eric Duminil
Eric Duminil

Reputation: 54223

Your data model is very redundant. You could use a dict with type as keys and list of quantities as values.

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'}]

res = {}

for d in data:
    res.setdefault(d['type'], []).append(d['quantity'])

print(res)
# {'Vip': [2, 23], 'Regular': [2, 2, 2, 2]}

The output is much shorter but you didn't lose any information.

If you're only interested in the total quantities, you could use a Counter:

from collections import Counter
count = Counter()
for d in data:
    count[d['type']] += d['quantity']

print(count)
# Counter({'Vip': 25, 'Regular': 8})
~                                         

Upvotes: 3

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476567

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

Upvotes: 10

Related Questions