Advertisement
Guest User

Untitled

a guest
May 26th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. #defaultdict will not always generate default value
  2. #if you didn't assign default data type to it, using defaultdict[key] to find the key might get an error
  3.  
  4. #defaultdict has default data type
  5. >>> x = defaultdict(int)
  6. >>> x
  7. defaultdict(<type 'int'>, {})
  8. >>> x["abc"]
  9. 0
  10. >>> x
  11. defaultdict(<type 'int'>, {'abc': 0})
  12.  
  13.  
  14. #defaultdict has no default data type
  15. >>> x = defaultdict()
  16. >>> x
  17. defaultdict(None, {})
  18. >>> x["abc"]
  19. Traceback (most recent call last):
  20. File "<stdin>", line 1, in <module>
  21. KeyError: 'abc'
  22.  
  23. #for safety, instead, we can use get() to find the key
  24. >>> x.get("abc") #will return nothing, but will not cause error
  25. >>>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement