Python Programming/Dictionaries

      A dictionary in Python is a collection of unordered values which are accessed by key.

      Dictionary notation

      Dictionaries may be created directly or converted from sequences. Dictionaries are enclosed in curly braces, {}

      >>> d = {'city':'Paris', 'age':38, (102,1650,1601):'A matrix coordinate'}
      >>> seq = [('city','Paris'), ('age', 38), ((102,1650,1601),'A matrix coordinate')]
      >>> d
      {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}
      >>> dict(seq)
      {'city': 'Paris', 'age': 38, (102, 1650, 1601): 'A matrix coordinate'}
      >>> d == dict(seq)
      True
      

      Also, dictionaries can be easily created by zipping two sequences.

      >>> seq1 = ('a','b','c','d')
      >>> seq2 = [1,2,3,4]
      >>> d = dict(zip(seq1,seq2))
      >>> d
      {'a': 1, 'c': 3, 'b': 2, 'd': 4}
      
      ↑Jump back a section

      Operations on Dictionaries

      The operations on dictionaries are somewhat unique. Slicing is not supported, since the items have no intrinsic order.

      >>> d = {'a':1,'b':2, 'cat':'Fluffers'}
      >>> d.keys()
      ['a', 'b', 'cat']
      >>> d.values()
      [1, 2, 'Fluffers']
      >>> d['a']
      1
      >>> d['cat'] = 'Mr. Whiskers'
      >>> d['cat']
      'Mr. Whiskers'
      >>> 'cat' in d
      True
      >>> 'dog' in d
      False
      
      ↑Jump back a section

      Combining two Dictionaries

      You can combine two dictionaries by using the update method of the primary dictionary. Note that the update method will merge existing elements if they conflict.

      >>> d = {'apples': 1, 'oranges': 3, 'pears': 2}
      >>> ud = {'pears': 4, 'grapes': 5, 'lemons': 6}
      >>> d.update(ud)
      >>> d
      {'grapes': 5, 'pears': 4, 'lemons': 6, 'apples': 1, 'oranges': 3}
      >>>
      
      ↑Jump back a section

      Deleting from dictionary

      del dictionaryName[membername]
      
      ↑Jump back a section
      Last modified on 10 November 2012, at 16:17