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'}, {'qua
Solution 1:
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)
.
Solution 2:
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})
~
Post a Comment for "Group List Of Dictionaries Python"