title: Why are values of a two-level dictionary all pointing to the same object in Python 2.7?
body: <p>I have tried to define a function to create a two-tiered dictionary, so it should produce the format</p>
  
  <pre><code>dict = {tier1:{tier2:value}}.
  </code></pre>
  
  <p>The code is:</p>
  
  <pre><code>def two_tier_dict_init(tier1,tier2,value):
      dict_name = {}
      for t1 in tier1:
          dict_name[t1] = {}
          for t2 in tier2:
              dict_name[t1][t2] = value
      return dict_name
  </code></pre>
  
  <p>So the following example...</p>
  
  <pre><code>tier1 = ["foo","bar"]
  tier2 = ["x","y"]
  value = []
  foobar_dict = two_tier_dict_init(tier1,tier2,value)
  </code></pre>
  
  <p>on the face of it produces what I want:</p>
  
  <pre><code>foobar_dict =  {'foo':{'x': [],'y':[]},
                  'bar':{'x': [],'y':[]}}                   }
  </code></pre>
  
  <p>However, when appending any value like</p>
  
  <pre><code>foobar_dict["foo"]["x"].append("thing")
  </code></pre>
  
  <p>All values get appended so the result is:</p>
  
  <pre><code>foobar_dict =  {'foo':{'x': ["thing"],'y':["thing"]},
                  'bar':{'x': ["thing"],'y':["thing"]}}
  </code></pre>
  
  <p>At first I assumed that due to the way my definition builds the dictionary that all values are pointing to the same space in memory, but I could not figure out why this should be the case. I then discovered that if I change the value from an empty list to an integer, when I do the following,</p>
  
  <pre><code>foobar_dict["foo"]["x"] +=1
  </code></pre>
  
  <p>only the desired value is changed.</p>
  
  <p>I must therefore conclude that it is something to do with the <code>list.append</code> method, but I can not figure it out. What is the explanation?</p>
  
  <p>N.B. I require this function for building large dictionaries of dictionaries where each tier has hundreds of elements. I have also used the same method to build a three-tiered version with the same issue occurring.</p>