Sha*_*ndo 2 python dictionary list python-3.x
我如何在列表中将字典的相似键分组
如果我有
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'}]
Run Code Online (Sandbox Code Playgroud)
我希望它像这样输出
res = {'Regular': [{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'}], 'Vip': [{'quantity': 23, 'type': 'Vip'},{'quantity': 23, 'type': 'Vip'}]}
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的代码,但是它给了我两倍的钥匙,可能是因为循环
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)
Run Code Online (Sandbox Code Playgroud)
我认为您没有完全理解a的想法defaultdict。defaultdict如果lookup中不存在任何对象,则A 将产生一个新对象。
因此,您可以简单地使用:
from collections import defaultdict
res = defaultdict(list)
for i in data:
res[i['type']].append(i)
Run Code Online (Sandbox Code Playgroud)
产生:
>>> 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'}]})
Run Code Online (Sandbox Code Playgroud)
(pprint是漂亮的打印,但不改变内容)。
请注意,这里我们将对字典的引用复制到新列表中,因此我们不会创建新字典。此外,结果是defaultdict。我们可以将它转换为一个香草与字典dict(res)。