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