【发布时间】:2019-04-02 16:02:31
【问题描述】:
我想按以下字典的值进行分组:
my_dict = {"Q1": {0: "no", 1: "yes"}, "Q2": {0: "no", 1: "yes"},
"Q3": {1: "animal", 2: "vehicle"}, Q4: {1: "animal", 2: "vehicle"}}
结果应该是这样的:
result = {("Q1", "Q2"): {0: "no", 1: "yes"},
("Q3", "Q4"): {1: "animal", 2: "vehicle"}}
我已经尝试过这里列出的解决方案: Grouping Python dictionary keys as a list and create a new dictionary with this list as a value
使用 collections.defaultdict 不起作用,因为结果会暗示我用作分组键的字典最终会成为结果字典的键,如下所示:
result = {{0: "no", 1: "yes"}: ["Q1", "Q2"] ,
{1: "animal", 2: "vehicle"}: ["Q3", "Q4"]}
当然这不起作用,因为字典的键必须是不可变的。所以我需要一个像frozendict这样的东西,这在python的标准库中是不可用的。
使用 itertools.groupby 也不起作用,因为它需要对数据进行排序。但是 operator.itemgetter 不能对字典进行排序。它说:
TypeError: '<' not supported between instances of 'dict' and 'dict'
因此,我想知道解决这个问题的 Pythonic 方法!谢谢你的帮助:)
【问题讨论】: