从包含另一个字典的字典制作边列表

Making an edge list from a dictionary that contains another dictionary

我的字典看起来像:

{
  a: {a, b, c},
  b: {a, b, c},
  ...
 }

本质上,一个包含键和值的字典,而值本身在另一个字典中。

如何将键和值制作成边缘列表

我希望每条边都像:

(a, a), (a, b), (a, c), (b, a), (b, b), (b, c)

对于字典中的每个键,它所连接的边就是它在字典中的值。

谢谢。

考虑到您有一本字典并且每个键的值都是一个集合,您可以试试这个:

a = 'a'
b = 'b'
c = 'c'


x = {
  a: {a, b, c},
  b: {a, b, c},
 }

for key in x:
    for value in x[key]:
        print("(" + key + ", " + value + ")", end=" ")

但是,您要求的顺序不能完全相同,因为字典和集合不是排序的数据结构。如果订单很重要,您可以使用以下代码:

a, b, c = 'a', 'b', 'c'

x = {
    a: {a, b, c},
    b: {a, b, c},
 }

y = []

for key in sorted(x):
    for value in sorted(x[key]):
        y.append((key, value))

print(y)

我真的希望这对您有所帮助。

a, b, c = ('a', 'b', 'c')
main = {a: {a, b, c}, b: {a, b, c}}

output = []

# loop through the keys of the dictionary
for key in main:
    # iterate through set
    for i in main[key]:
        output.append((key, i))

print(output)
>>> [('a', 'a'), ('a', 'c'), ('a', 'b'), ('b', 'a'), ('b', 'c'), ('b', 'b')]

虽然我不清楚您正在寻找的确切边缘情况,但作为@double_j结果的替代方案,您可以对键和值执行itertools.product

import itertools as it

list(it.product(main.keys(), set.union(*main.values())))
# [('a', 'a'), ('a', 'c'), ('a', 'b'), ('b', 'a'), ('b', 'c'), ('b', 'b')]

此方法找到两个可迭代对象的 Cartesian product:1) 键和 2) main 字典中的一组唯一值。