首页 > 解决方案 > 当值是列表时,将 dict 中具有相同值的所有键分组

问题描述

我有一个字典:

my_dict = {
  'train_1': ['a', 'b','c'],
  'train_2': ['a', 'b', 'c', 'd'],
  'train_3': ['a', 'b', 'c', 'd'],
  'train_4': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
  'train_5': ['a', 'b', 'c', 'd', 'e', 'f'],
  'train_6': ['a', 'b', 'c', 'd']
}

我需要在字典中找到具有相同列表的所有键。

输出应该是:

{
  'group_1': ['train1'],
  'group_2': ['train_2', 'train_3', 'train_6'],
  'group_3': ['train_4'],
  'group_4': ['train_5'],
}

当 dict 中的值不是列表时,我可以对任务使用类似的东西:

flipped = {}

for key, value in my_dict.items():
    print(value)
    if value not in flipped:
        flipped[value] = [key]
    else:
        flipped[value].append(key)

但是当值是列表时,我该如何实现呢?

标签: pythondictionary

解决方案


继续评论,您可以将列表更改为元组,然后将它们用作键:

my_dict = {
  'train_1': ['a', 'b','c'],
  'train_2': ['a', 'b', 'c', 'd'],
  'train_3': ['a', 'b', 'c', 'd'],
  'train_4': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'],
  'train_5': ['a', 'b', 'c', 'd', 'e', 'f'],
  'train_6': ['a', 'b', 'c', 'd']
}

flipped = {}

for key, value in my_dict.items():
    if tuple(value) not in flipped:
        flipped[tuple(value)] = [key]
    else:
        flipped[tuple(value)].append(key)
print(flipped)

输出:

{('a', 'b', 'c'): ['train_1'], ('a', 'b', 'c', 'd'): ['train_3', 'train_6', 'train_2'], ('a', 'b', 'c', 'd', 'e', 'f'): ['train_5'], ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
: ['train_4']}     

编辑

一次,过滤。您可以遍历新的 dict 并分配所需的键:

grouped_dct = {}
i = 1
for k,v in flipped.items():
    grouped_dct['group_' + str(i)] = v
    i += 1

打印(grouped_dct)

输出:

{'group_1': ['train_4'], 'group_2': ['train_5'], 'group_3': ['train_2', 'train_6', 'train_3'], 'group_4': ['train_1']}  

                                                                                                                                                          

推荐阅读