字典python的组列表 [英] Group list of dictionaries python
问题描述
如何将字典中相似的键分组到列表中
How can i group similar keys of a dictionary in a list
如果我有
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)
推荐答案
我认为您不完全了解 defaultdict
的想法.如果在查找时不存在 defaultdict
,则会产生一个新对象.
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)
产生:
>>> 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
是漂亮打印,但不会更改内容).
(pprint
is pretty print, but does not change the content).
请注意,这里我们将 reference 复制到字典到新列表中,因此我们不会创建新字典.此外,结果是 defaultdict
.我们可以使用 dict(res)
将其转换为 vanilla 字典.
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)
.
这篇关于字典python的组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!