Scripting >> Python >> Dictionaries >> Notes on dictionaries in Python

(1) to initialize dictionary
  purse = dict()
  purse['money'] = 12
  or
  purse = {}

  or

  purse = {'money':12}

(2) how to set default initial value of a dictionary item

  purse[money] = purse.get(money,0)

(3) how to increment dictionary value without traceback
  purse[money] = purse.get(money,0) + 1
  if don't exist initialize first with 0 and then add
  if exist, get the current value then add

(4) how to print various parts of the dict

     a.  print the keys either by
          print list(purse)
          or
          print purse.keys()

      b. print the values by
          print purse.values()

      c. print individual dictionary items in key,value (tuples) format
          print purse.items()
   
          output will look like the following:

          [('money',12),('tissues',1)]

(5) how to loop through tuples in the dictionary
      e.g. loop through
             purse = {'money':12,'tissues':2}
             for item,qty in purse.items()
                 print item,qty

(6) what are the ways to so sort a dictionary by key

      for key in sorted(mydict) :
          print key, mydict[key]