Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于公共元素合并python字典键_Python_Loops_Dictionary_Merge_Key - Fatal编程技术网

基于公共元素合并python字典键

基于公共元素合并python字典键,python,loops,dictionary,merge,key,Python,Loops,Dictionary,Merge,Key,假设我们有这样一本词典: {0: [2, 8], 1: [8, 4], 3: [5]} 然后我们遇到一个键值对2,8。现在,由于键0的值2和8已经出现,我需要合并前两个键并创建一个新字典,如下所示: {0: [2, 8, 4], 3: [5]} 我知道可以进行大量的循环和删除。我真的在寻找一种更像蟒蛇的方式 提前谢谢。你的同事稍后会恨你的,但是在这里 d = {0: [2, 8], 1: [8, 4], 3: [5]} revmap = {} for k,vals

假设我们有这样一本词典:

{0: [2, 8], 1: [8, 4], 3: [5]}
然后我们遇到一个键值对2,8。现在,由于键0的值28已经出现,我需要合并前两个键并创建一个新字典,如下所示:

{0: [2, 8, 4], 3: [5]} 
我知道可以进行大量的循环和删除。我真的在寻找一种更像蟒蛇的方式


提前谢谢。

你的同事稍后会恨你的,但是在这里

d = {0: [2, 8], 
     1: [8, 4], 
     3: [5]}

revmap = {}
for k,vals in d.items():
    for v in vals:
        revmap[k] = v

k,v = 2,8
d[revmap[k]].extend([i for i in d[revmap[v]] if i not in d[revmap[k]]])
d.pop(revmap[v])
>>> d = {0: [2, 8], 1: [8, 4], 3: [5]}
>>> x = ((a,b) for a,b in itertools.combinations(d,2) if a in d and b in d and set(d[a]).intersection(d[b]))
>>> for a,b in x:d[min(a,b)].extend([i for i in d[max(a,b)] if i not in d[min(a,b)]]) or d.pop(max(a,b))
[8, 4]
>>> d
{0: [2, 8, 4], 3: [5]}

你的同事以后会恨你的,但是在这里

>>> d = {0: [2, 8], 1: [8, 4], 3: [5]}
>>> x = ((a,b) for a,b in itertools.combinations(d,2) if a in d and b in d and set(d[a]).intersection(d[b]))
>>> for a,b in x:d[min(a,b)].extend([i for i in d[max(a,b)] if i not in d[min(a,b)]]) or d.pop(max(a,b))
[8, 4]
>>> d
{0: [2, 8, 4], 3: [5]}

键值对2,8-结果中的键
2
在哪里?那么键
1
发生了什么事?@thefourtheye:也许因为传入键是2,所以包含传入键的键(在本例中,
0
)优先?很抱歉,它将是键0,而不是键1。如果原始字典包含
3:[5,8]
?因为我正在动态创建字典,这不会发生。因为3、5和8已经与键0合并。键值对2、8-结果中的键
2
在哪里?那么键
1
发生了什么事?@thefourtheye:也许因为传入键是2,所以包含传入键的键(在本例中,
0
)优先?很抱歉,它将是键0,而不是键1。如果原始字典包含
3:[5,8]
?因为我正在动态创建字典,这不会发生。因为3、5和8已经与键0合并。