为了账号安全,请及时绑定邮箱和手机立即绑定

如何在python中将字典与字典分组?

如何在python中将字典与字典分组?

SMILET 2022-05-11 15:48:08
我需要按组的值对下面的字典进行分组,输出想要有这样的值。当前结构:{'sfp_dnscommonsrv': {'object': <modules.sfp_dnscommonsrv.sfp_dnscommonsrv object at 0x7f448bd6ac50>, 'name': 'DNS Common SRV', 'cats': ['Footprint', 'Investigate', 'Passive'], 'group': 'DNS', 'labels': ['']}, sfp__stor_db': {'object': <modules.sfp__stor_db.sfp__stor_db object at 0x7f448bd6acc0>, 'name': 'Storage', 'cats': [''], 'group': 'DNS', 'labels': ['']}}成功:{'DNS': [{value where group is DNS}, {value where group is DNS}], 'DNS2': [{value where group is DNS2}]},简单版:数据:{'wood': {'color': 'red', 'group': 'old'}, 'stone': {'color': 'gray', 'group': 'old'}, 'glass': {'color': 'white', 'group': 'new'}}结果:{'old': [{'color': 'red', 'material': 'wood'},{'color': 'gray', 'material': 'stone'}], 'new': [{'color': 'white', 'material': 'glass'}]}
查看完整描述

1 回答

?
互换的青春

TA贡献1797条经验 获得超6个赞

您可以使用单线itertools.groupby来实现这一目标。

但首先有几点需要澄清:

  • 在您的简单版本中,您有一个group未定义的键。我只是假设这是一个字符串:'group'

  • 输入数据中不存在所需输出中的键'material',因此我将在构建结果字典期间添加此键,使用输入数据中的值作为此新键的值。

  • 简单地按一个键分组不会自动从字典中删除这个键值对,所以分组后你的字典中仍然会有你的“组”键。

所以这就是你的groupby样子:

from itertools import groupby


init_data = {'wood': {'color': 'red', group: 'old'}, 'stone': {'color': 'gray', group: 'old'}, 'glass': {'color': 'white', group: 'new'}}


# this is in a one-liner, however I added some newlines for readability :)

grouped_data = {

    k: list(

        {

            _k: _v for d in (

                {'material': av[0]},  # this is just to add the 'material' key

                av[1]

            ) for _k,_v in d.items()

        } for av in v

        ) for k, v in groupby(

            init_data.items(),

            lambda x: x[1]['group']

        )

    }

grouped_data


Out[7]: {'new': [{'color': 'white', 'group': 'new', 'material': 'glass'}],

 'old': [{'color': 'gray', 'group': 'old', 'material': 'stone'},

  {'color': 'red', 'group': 'old', 'material': 'wood'}]}


查看完整回答
反对 回复 2022-05-11
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号