简体   繁体   English

将一个字典中的带有空列表的键与另一个包含该键作为值的字典合并后找到最小的集合

[英]Find the smallest set after merging key with empty list from one dictionary with another dictionary containing that key as value

I have two dictionaries in Python 3-x.:我在 Python 3-x 中有两个字典:

A = {1: [9], 7: [], 14: [], 32: [9], 40: []}

and

B = {1: [7, 9, 10], 7: [1, 14], 14: [7, 40], 32: [9, 40], 40: [14, 32]}

I want to find, for those empty lists as values in dict A, the key, contained as values in dict B. Then, merge that key from dict A to the value list, containing the key from A and output the shortest set of combined key and value merger.对于那些作为dict A中的值的空列表,我想找到作为dict B中的值包含的键。然后,将该键从dict A合并到值列表中,其中包含来自A和output的键的最短组合键值合并。

For example, key 7 in dict A has an empty list as value.例如,dict A 中的键 7 有一个空列表作为值。 So we look, which value lists in B contains key 7. We see that 1: [7, 9, 10] and 14: [7, 40] contains "7" as value.所以我们看,B 中的哪个值列表包含键 7。我们看到 1: [7, 9, 10] 和 14: [7, 40] 包含“7”作为值。 So perform a merger to output the sets: {1, 7, 9, 10} and {14, 40, 7}.所以合并到 output 集合:{1, 7, 9, 10} 和 {14, 40, 7}。 From these two sets, the final output should be the smallest set, ie, {14, 40, 7}.从这两个集合中,最终的 output 应该是最小的集合,即{14, 40, 7}。 Note: If both sets are same size, I would like to choose the first one.注意:如果两套尺寸相同,我想选择第一套。 The same goes for the keys 14 and 40 in dict A. dict A 中的键 14 和 40 也是如此。

So far, I have tried the following:到目前为止,我已经尝试了以下方法:

temp3 = []
for k, v in A.items():
 if len(v) == 0:
       s3 = set()
       for i,j in B.items():
           if k in j:
               lst = []
               lst.append(j)
               min_list = min(lst)
               s3 = set(min_list)
               s3.add(k)
               s3.add(i)
               temp3.append(s3)
               C = set()
               for i in temp3:
                   C = set(i)
               print("temp3 for", k, "is", C)

The output is: output 是:

temp3 for 7 is {9, 1, 7, 10}
temp3 for 7 is {40, 14, 7}
temp3 for 14 is {1, 14, 7}
temp3 for 14 is {32, 40, 14}
temp3 for 40 is {40, 14, 7}
temp3 for 40 is {40, 9, 32}

I can perform the mergers.我可以执行合并。 But I cannot figure out how to get the smallest set as output as describes above.但我无法弄清楚如何获得最小的集合作为 output 如上所述。 Please help.请帮忙。

It's easier if you use an iterable of the candidate sets and use min on it:如果您使用候选集的可迭代并在其上使用min会更容易:

for a in A:
    if not A[a]:
        sets = ({b, *B[b]} for b in B if a in B[b])
        print(a, min(sets, key=len))

Output: Output:

7 {40, 14, 7}
14 {1, 14, 7}
40 {40, 14, 7}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM