title: adding entries to a dictionary if it doesn't exist already
body: <p>I'm trying to write some code that calculates powers of 2 but stores them in a dictionary that has powers of 10 as the key, so for example, 2^9 would be stored as</p>
  
  <pre><code>{0:2, 1:1, 2:5}
  </code></pre>
  
  <p>where you have 5*10^2 + 1*10^1 + 2*10^0.</p>
  
  <p>So currently, I have something like </p>
  
  <pre><code>def foo():
      result={0:2}
      for i in range(2,10):
          for p in result.keys():
              result[p]*=2
          for p in result.keys():
              if result[p] / 10 != 0:
                  result.setdefault(p+1,result[p]/10)
                  result[p] = result[p] % 10
  </code></pre>
  
  <p>The issue is</p>
  
  <pre><code>result.setdefault(p+1,result[p]/10)
  </code></pre>
  
  <p>It overwrites whatever was in <code>result[p+1]</code>.  I know it's possible to just check the dictionary and then "initialize" the new key if needed, but is there a more elegant way to do it on the fly?  I could initialize result to be long enough, but since I don't necessarily know how long is "long enough", it seems to me to make more sense to extend it on the fly.</p>
  
  <p>Basically I'd like something along the lines of</p>
  
  <pre><code>for p in result.keys():
      if result[p] / 10 != 0:
          if result[p+1] exists:
              result[p+1]+=result[p]/10
          else:
              create result[p+1] and set its value to result[p]/10
  </code></pre>
  
  <p>Any help is much appreciated!</p>