Main.Dictionaries History

Hide minor edits - Show changes to markup

March 21, 2010, at 09:40 PM MST by 71.196.160.210 -
Added lines 1-71:

(:source lang=python:)

"""Python dictionaries http://openbookproject.net/thinkcs/python/english2e/ch12.html """

  1. a dictionary is a collection of key-value pairs that allows access
  2. to the value by key
  3. create an empty dictionary

eng2sp = {} eng2sp['one'] = 'uno' eng2sp['two'] = 'dos'

  1. why is this useful? how would you implement something like this using
  2. a list?

print eng2sp

  1. you can create a dictionary by providing key-value pairs in the same
  2. format as the output of the above output:

eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}

  1. order doesn't matter!

inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print inventory

  1. the len function returns the number of key-value pairs

print len(inventory)

  1. We can change the values in a dictionary:

inventory['pears'] = 0

  1. and delete key-value pairs:

del inventory['pears']

  1. you can determine if a dictionary has an entry with a given key:

print 'pears' in inventory print 'bananas' in inventory

  1. you can use integers, strings and tuples as keys:

pair_dictionary = {} pair_dictionary[('a', 1)] = 1 pair_dictionary[('z', 3)] = 5

  1. note that all keys of a dictionary are immutable
  2. you can iterate over a dictionary using a for loop:

for key in inventory :

    print inventory[key]
  1. examples where this is useful:

def count_letters(s) :

    counts = {}
    for char in s :
        if not(char in counts) :
            counts[char] = 0
        counts[char] += 1
    return counts

(:sourceend:)