在字典中添加要设置的多个元素

时间:2016-09-08 22:32:12

标签: 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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

outputCsvRdd.saveAsTextFile('OUTPUTPATH')需要可迭代的值。使用set.add()添加一个值:

set.update()

不是每次都测试if value[0] in temp_dict: temp_dict[value[0]].add(value[1]) ,而是在缺少密钥时使用dict.setdefault()设置空集:

value[0]

答案 1 :(得分:1)

您可以defaultdict使用set作为默认值。

from collections import defaultdict

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 = []

    def enter_edges(self, source, dest):
        self.edges.extend([(source, dest)])

    def form_graph_structure(self):
        temp_dict = defaultdict(set)
        for pair in self.edges:
            source, dest = pair
            temp_dict[source].add(dest)
        print temp_dict

    def display(self):
        print dict(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()
{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):
        self.graph = defaultdict(set)

    def enter_edges(self, source, dest):
        self.graph[source].add(dest)

    def display(self):
        print dict(self.graph)

g = Graph()
edges = [(2, 0), (2, 3), (0, 1), (1, 2), (3, 3)]
for pair in edges:
    g.enter_edges(*pair)
g.display()
{0: set([1]), 1: set([2]), 2: set([0, 3]), 3: set([3])}