[英]Combining the Values from Multiple Keys in Dictionary Python
In Python, I have the following dictionary of sets: 在Python中,我具有以下集合的字典:
{
1: {'Hello', 'Bye'},
2: {'Bye', 'Do', 'Action'},
3: {'Not', 'But', 'No'},
4: {'No', 'Yes'}
}
My goal is combine the keys which contain match values (like in this example, "Bye" and "No"), so the result will look like this: 我的目标是合并包含匹配值的键(例如在此示例中,“再见”和“否”),因此结果将如下所示:
{
1: {'Hello', 'Bye', 'Do', 'Action'},
3: {'Not', 'But', 'No', 'Yes'}
}
Is there a way to do this? 有没有办法做到这一点?
If there are overlapping matches and you want the longest matches: 如果存在重叠的匹配项,而您想要最长的匹配项:
from collections import defaultdict
d = {
1: {'Hello', 'Bye'},
2: {'Bye', 'Do', 'Action'},
3: {'Not', 'But', 'No'},
4: {'No', 'Yes'}
}
grp = defaultdict(list)
# first group all keys with common words
for k, v in d.items():
for val in v:
grp[val].append(k)
# sort the values by lengths to find longest matches.
for v in sorted(grp.values(), key=len, reverse=True):
for val in v[1:]:
if val not in d:
continue
# use first ele as the key and union to existing values
d[v[0]] |= d[val]
del d[val]
print(d)
if you don't have overlaps you can just: 如果没有重叠,您可以:
grp = defaultdict(list)
for k, v in d.items():
for val in v:
grp[val].append(k)
for v in grp.values():
for val in v[1:]:
d[v[0]] |= d[val]
del d[val]
Or if you want a new dict: 或者,如果您想要一个新的字典:
new_d = {}
for v in grp.values():
if len(v) > 1:
k = v[0]
new_d[k] = d[k]
for val in v[1:]:
new_d[k] |= d[val]
All three give you the following but key order could be different: 这三个都为您提供以下内容,但关键顺序可能有所不同:
{1: set(['Action', 'Do', 'Bye', 'Hello']), 3: set(['Not', 'Yes', 'But', 'No'])}
If there is no overlapping matches: 如果没有重叠的匹配项:
a = {1: {'Hello', 'Bye'}, 2: {'Bye', 'Do', 'Action'}, 3: {'Not', 'But', 'No'}, 4: {'No', 'Yes'}}
output = {}
for k, v in a.items():
if output:
for k_o, v_o in output.items():
if v_o.intersection(v):
output[k_o].update(v)
break
else:
output[k] = v
else:
output[k] = v
print(output)
Output: 输出:
{1: {'Action', 'Bye', 'Do', 'Hello'}, 3: {'But', 'No', 'Not', 'Yes'}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.