python - 将多个元素添加到字典中的集合

标签 python graph set

我正在尝试实现以下结构。

{0: set([1]), 1: set([2]), 2: set([0,3]), 3: set([3])}

以下是我的代码:

class Graph(object):
    """ This is the graph class which will store the information regarding
        the graph like vertices and edges.
    """

    def __init__(self,num_vertices):
        self.vertices = num_vertices
        self.edges = []
        self.indi_edges = ()

    def enter_edges(self,source,dest):
        self.indi_edges = (source, dest)
        self.edges.append(self.indi_edges)

    def form_graph_structure(self):
        temp_dict = {}
        for idx,value in enumerate(self.edges):
            if value[0] in temp_dict:
                print "here"
                temp_dict[value[0]].update(value[1])
            print "there"
            temp_dict[value[0]] = set()
            temp_dict[value[0]].add(value[1])
        print temp_dict


    def display(self):
        print self.edges

g = Graph(4)
g.enter_edges(2,0)
g.enter_edges(2,3)
g.enter_edges(0,1)
g.enter_edges(1,2)
g.enter_edges(3,3)
g.form_graph_structure()

我收到以下错误

  File "DFS.py", line 20, in form_graph_structure
    temp_dict[value[0]].update(value[1])
TypeError: 'int' object is not iterable

有人可以帮忙吗?

最佳答案

set.update() 需要一个 iterable 值。使用 set.add()添加一个值:

if value[0] in temp_dict:
    temp_dict[value[0]].add(value[1])

与其每次都测试 value[0],不如使用 dict.setdefault()如果缺少 key ,则设置一个空集:

def form_graph_structure(self):
    temp_dict = {}
    for source, dest in self.edges:
        temp_dict.setdefault(source, set()).add(dest)
    return temp_dict

关于python - 将多个元素添加到字典中的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39401150/

相关文章:

Python:枚举的切片

java - 在内存中存储父子映射。有效地为 parent 列出所有可达的 child

一个集合的所有可能集合列表的算法

c++ - C++ STL 容器集的奇怪行为

javascript - 如何创建像堆栈溢出这样的响应图?

math - 确定性有限状态自动机问题

c++ - 共享库符号名称

python - PySpark distinct().count() 在 csv 文件上

python - Django 从所有查询中排除字段

c++ - 找到散列映射的最大独立子组的算法