python - 当值是列表时,将 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)
但是当值是列表时,我该如何实现呢?
解决方案
继续评论,您可以将列表更改为元组,然后将它们用作键:
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']}
推荐阅读
- java - 对象引用在不使用时被删除?
- android - 连接 PubNub 服务的频道时出现 PNTimeoutCategory 错误
- python - Python Pandas - 查找和分组异常值
- javascript - 为创建和编辑页面使用相同表单组件的良好做法
- flutter - 文本从大到小的颤动动画
- windows - Windows 上的 Flutter:如何调用外部 dll?
- c# - 是否可以创建连接到另一个 websocket 的 websocket 服务器?
- jodatime - 为什么 kotlinx-datetime 存在?或者:为什么数据时间库如此依赖于平台?
- azure - Azure DevOps API - 如何引用其他管道作为资源参数
- typescript - 如何避免 VSCode 自动补全中的省略号?