Group list of dictionaries python

筅森魡賤 提交于 2021-02-04 19:51:53

问题


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)

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




回答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})
~                                         


来源:https://stackoverflow.com/questions/46844833/group-list-of-dictionaries-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!