Python Recipes

It has been months since i wrote something here.During the intervening time i happened to see ‘Python Cookbook’ and i am publishing my notes and examples here,hoping that someone like me will find them useful.

  • Swapping Values Without Using a Temporary Variable
  • In python we don’t have to use temporary variables to swap variable values.Python’s automatic tuple packing and unpacking make this a snap:

    a, b, c = b, c, a

  • Constructing a Dictionary Without Excessive Quoting
  • When the keys are identifiers, a cleaner way is

  • Getting a Value from a Dictionary
  • We need to obtain a value from a dictionary, without having to handle an exception if the key you
    seek is not in the dictionary.We usually use like

    let d = {‘a’:1, ‘b’:2 ,’c’:3} is the dictionary then

    if d.has_key('a'):
        print d['a']
    else:
        print 'not found'
    

    However, there is a much simpler syntax:

    print d.get('a', 'not found')
    

    Example:

    Leave a comment

    Design a site like this with WordPress.com
    Get started