合并套Python字典 [英] merge python dictionary of sets

查看:109
本文介绍了合并套Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2种的节点 - 的信节点的(L)和'编号节点'(N)的曲线图。我有2个字典,​​一是表明由L边缘N和其他节目边从N到L;

I have a graph with 2 kinds of nodes- 'Letter nodes' (L) and 'Number nodes' (N). I have 2 dictionaries, one shows edges from L to N and the other shows edges from N to L.

 A = {0:(b,), 1:(c,), 2:(c,), 3:(c,)}
 B = {a:(3,), b:(0,), c:(1,2,3)} 

有一个键,值对 C:(1,2,3)意味着有来自 C 边缘 1,2,3 (3边)

A key,value pair c:(1,2,3) means there are edges from c to 1,2,3 (3 edges)

我想这些合并成一个字典 C ,这样的结果是一个新的字典:

I want to merge these to one dictionary C so that the result is a new dictionary:

C = {(0,): (b,), (1, 2, 3): (a, c)}

C = {(b,):(0,), (a, c):(1, 2, 3)}

在生成的词典我想信节点和数字节点上的键和值的不同侧面。我不在乎它只是需要他们分开的键或值。我该如何去有效地解决这个?

In the resulting dictionary I want the letter nodes and numerical nodes to be on separate sides of keys and values. I don't care which is the key or value just need them separated. How can I go about solving this efficiently?

澄清:这与2类型的节点的图的 - 号节点,和信节点。字典Ç说,从信节点(A,C)可以(1,2,3),即A-> 3-> C-> 1,A-> 3-> C-> 2从而达到数量的节点就可以得到1,2,3从。虽然没有直接的EDGE从A到2或1。

CLARIFICATION: this of a graph with 2 types of nodes - number nodes, and letter nodes. the dictionary C says from letter nodes (a,c) you can reach the number nodes (1,2,3) i.e a->3->c->1, a->3->c->2 thus you can get to 1,2,3 from a. EVEN THOUGH THERE IS NO DIRECT EDGE FROM a to 2 or a to 1.

推荐答案

根据你的说法,我猜你正在努力寻找一个图算法。

According to your statement, I guess you are trying to find a graph algorithms.

import itertools
def update_dict(A, result): #update vaules to the same set
    for k in A:
        result[k] = result.get(k, {k}).union(set(A[k]))
        tmp = None
        for i in result[k]:
            tmp = result.get(k, {k}).union(result.get(i, {i}))
        result[k] = tmp
        for i in result[k]:
            result[i] = result.get(i, {i}).union(result.get(k, {k}))

A = {0:('b',), 1:('c',), 2:('c',), 3:('c',)}
B = {'a':(3,), 'b':(0,), 'c':(1,2,3)}
result = dict()
update_dict(A, result)
update_dict(B, result)
update_dict(A, result) #update to fix bugs
update_dict(B, result)

k = sorted([sorted(list(v)) for v in result.values()]) 
k = list( k for k, _ in itertools.groupby(k))  #sort and remove dumplicated set

final_result = dict()
for v in k: #merge the result as expected
    final_result.update({tuple([i for i in v if isinstance(i, int)]):tuple([i for i in v if not isinstance(i, int)])})
print final_result

#output
{(0,): ('b',), (1, 2, 3): ('a', 'c')}

这篇关于合并套Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆