Add multiple Elements to Set in a Dictionary
<p>I am trying to achieve the following structure.</p>

<pre><code>{0: set([1]), 1: set([2]), 2: set([0,3]), 3: set([3])}
</code></pre>

<p>Following is my code : </p>

<pre><code>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()
</code></pre>

<p>I am getting the following error</p>

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

<p>Can anyone help? </p>

<p><code>set.update()</code> expects an <em>iterable</em> of values. Use <a href="https://docs.python.org/2/library/stdtypes.html#set.add" rel="nofollow"><code>set.add()</code></a> to add <em>one</em> value:</p>

<pre><code>if value[0] in temp_dict:
    temp_dict[value[0]].add(value[1])
</code></pre>

<p>Rather than test for <code>value[0]</code> each time, use <a href="https://docs.python.org/2/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>dict.setdefault()</code></a> to set an empty set if the key is missing:</p>

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

python graph set