簡體   English   中英

合並python集字典

[英]merge python dictionary of sets

我有一個帶有2種節點的圖-“字母節點”(L)和“數字節點”(N)。 我有2個字典,一個顯示從L到N的邊緣,另一個顯示從N到L的邊緣。

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

鍵值對c:(1,2,3)表示存在從c1,2,3邊(3個邊)

我想將它們合並到一個字典C以便結果是一個新字典:

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

要么

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

在生成的字典中,我希望字母節點和數字節點位於鍵和值的不同側。 我不在乎哪個是鍵或值,只需要將它們分開即可。 我該如何有效地解決這個問題?

澄清:這是一種具有2種類型的節點的圖-數字節點和字母節點。 字典C說從字母節點(a,c)可以到達數字節點(1,2,3),即a-> 3-> c-> 1,a-> 3-> c-> 2因此您可以從a到1,2,3 即使從a到2或a到1都沒有直接邊緣。

根據您的陳述,我想您正在嘗試找到一種圖形算法。

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')}

因此,我目前尚不確定這是否是最有效的方法,但它的工作原理是:

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

# Put B in the same form as A

B_inv = {}
for k, v in B.items():
    for i in v:
        if B_inv.get(i) is not None:
            B_inv[i] = B_inv[i].union(k)
        else:
            B_inv[i] = set(k)

B_inv = {k: tuple(v) for k, v in B_inv.items()}
AB = set(B_inv.items() + A.items())  # get AB as merged

這使您合並了詞典。 從這里:

new_dict = {}
for a in AB:
    for i in a[1]:
        if new_dict.get(i) is not None:
            new_dict[i] = new_dict[i].union([a[0]])
        else:
            new_dict[i] = set([a[0]])

# put in tuple form
new_dict = {tuple(k): tuple(v) for k,v in new_dict.items()}

這給了我:

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

基本上,我依靠集合的可變性及其消除重復項的內置功能,以嘗試使每個字典中的循環數保持最小。 除非我錯過任何事情,否則應該是線性時間。

從這里開始,我需要進行比較,並再次依賴於集合,以防止我需要對每個單個元素進行最壞情況的成對比較。

merge_list = []

for k, v in new_dict.items():
    matched = False
    nodeset = set([k[0]]).union(v)
    for i in range(len(merge_list)):
        if len(nodeset.intersection(merge_list[i])) != 0:
            merge_list[i] = merge_list[i].union(nodeset)
            matched = True

    # did not find shared edges
    if not matched:
        merge_list.append(nodeset)

最后,將其轉換為具有單個“層”和元組的形式。

C = {}

for item in merge_list:
    temp_key = []
    temp_val = []

    for i in item:
        if str(i).isalpha():
            temp_key.append(i)
        else:
            temp_val.append(i)

    C[tuple(temp_key)] = tuple(temp_val)

C給我{('a', 'c'): (1, 3, 2), ('b',): (0,)}

嘗試這個:

c = a.copy()
c.update(b)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM