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

我需要按组的值对下面的字典进行分组,输出想要有这样的值。


当前结构:


{'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'}]}



SMILET
浏览 146回答 1
1回答

互换的青春

您可以使用单线itertools.groupby来实现这一目标。但首先有几点需要澄清:在您的简单版本中,您有一个group未定义的键。我只是假设这是一个字符串:'group'。输入数据中不存在所需输出中的键'material',因此我将在构建结果字典期间添加此键,使用输入数据中的值作为此新键的值。简单地按一个键分组不会自动从字典中删除这个键值对,所以分组后你的字典中仍然会有你的“组”键。所以这就是你的groupby样子:from itertools import groupbyinit_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 = {&nbsp; &nbsp; k: list(&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; _k: _v for d in (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {'material': av[0]},&nbsp; # this is just to add the 'material' key&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; av[1]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ) for _k,_v in d.items()&nbsp; &nbsp; &nbsp; &nbsp; } for av in v&nbsp; &nbsp; &nbsp; &nbsp; ) for k, v in groupby(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; init_data.items(),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; lambda x: x[1]['group']&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }grouped_dataOut[7]: {'new': [{'color': 'white', 'group': 'new', 'material': 'glass'}],&nbsp;'old': [{'color': 'gray', 'group': 'old', 'material': 'stone'},&nbsp; {'color': 'red', 'group': 'old', 'material': 'wood'}]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python