1

I am trying to add an element to a set within a dictionary in Python, but when I use mydictionary[index].update([newelement]), all the dictionary is being updated with the newelement. Here goes the python console commands and outputs to demonstrate what I am saying:

>>> graph=dict.fromkeys(range(10),set([]))
>>> graph
{0: set([]), 1: set([]), 2: set([]), 3: set([]), 4: set([]), 5: set([]), 6: set([]), 7: set([]), 8: set([]), 9: set([])}
>>> graph[0].update([1])
>>> graph
{0: set([1]), 1: set([1]), 2: set([1]), 3: set([1]), 4: set([1]), 5: set([1]), 6: set([1]), 7: set([1]), 8: set([1]), 9: set([1])}

So why isn't updating only the entry for graph[0]?

I really tried to find a topic with this question specifically, but I didn't find one.

Obs: The parenthesis with numbers are the commands in python console.

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160

2 Answers2

1

dict.fromkeys creates a dictionary with keys from the first item you put in and with values that are the second element. In other words, all of the values are referencing the same object.

This is the same as if:

a = set()
b = a
b.add('foo')
print a

In this case, you'll see that both a and b have an element 'foo'. Now look at their IDs:

print id(a)
print id(b)

Notice that it's the same number because they are the same object.

mgilson
  • 300,191
  • 65
  • 633
  • 696
1

The variable graph isn't 10 sets, it's a ten-element dictionary, where each value references the same set. Thus, modifying the contents of one set modifies them all.

>>> graph=dict.fromkeys(range(10),set([]))
>>> id(graph[0]), id(graph[1])
(140681644256512, 140681644256512)
johntellsall
  • 14,394
  • 4
  • 46
  • 40