python 字典组列表

2023-11-30

如何将字典中的相似键分组到列表中

如果我有

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 = {'Regular': [{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'},{'quantity': 2, 'type': 'Regular'}], 'Vip': [{'quantity': 23, 'type': 'Vip'},{'quantity': 23, 'type': 'Vip'}]}

这是我尝试过的代码,但它给了我双倍的密钥,可能是因为循环

 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)

我认为你没有完全理解a的想法defaultdict. A defaultdict如果不存在,将产生一个新对象查找时.

所以你可以简单地使用:

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 is pretty打印,但不改变内容)。

注意这里我们复制到那里参考将字典添加到新列表中,因此我们不创建新字典。此外,结果是defaultdict。我们可以将它投射到vanilla字典与dict(res).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python 字典组列表 的相关文章

随机推荐