-1

I have created a default dictionary as below :

from collections import defaultdict
dd = defaultdict(lambda : "Key not    found")
dd = {'a':1,'b':2}
print(dd) 
print(dd['a']) # Prints 1
print(dd['c'])  # Throws KeyError

But, the below code snippet works :

from collections import defaultdict
(lambda : "Key not    found")
dd['a']=1
dd['b']=2
print(dd) 
print(dd['a']) # Prints 1
print(dd['c'])  # Prints "Key not found"

Could anyone please explain me why the first code snippet throws error whereas the second one runs fine as expected..

Shraddha
  • 791
  • 7
  • 13

3 Answers3

2

You have overwritten dd = defaultdict(lambda : "Key not found") with dd = {'a':1,'b':2} so that defaultdict() has became a dict().

SanthoshSolomon
  • 1,383
  • 1
  • 14
  • 25
1

Please consider to delete the line 3 in the first snippet. That has overwritten your dd whose type is defaultdict.

sinwoobang
  • 138
  • 10
0

The problem is in the below two lines of your code snippet -

dd = defaultdict(lambda : "Key not    found")
dd = {'a':1,'b':2}

In the first line, you are creating a defaultdict object and dd is pointing to this object - dict_object

In the second line, you are creating a dictionary and now, saving its reference to dd - enter image description here So, now as you can see in the picture above that dd is pointing to a new dictionary created in second line. And since, this new dictionary which dd is referring to is not having a key named 'c', you are getting a Key not found error.

Shraddha
  • 791
  • 7
  • 13