Python 3

home

Introduction to Python

davidbpython.com




Dictionaries: Lookup Tables

dictionaries

A dictionary (or dict) is a collection of unique key/value pairs of objects.


mydict = {}                      # empty dict

mydict = {'a':1, 'b':2, 'c':3}   # dict with str keys and int values

print(mydict['a'])               # look up 'a' to get 1





example uses: dictionaries

Pairs describe data relationships that we often want to consider:


You yourself may consider data in pairs, even in your personal life:





types of dictionaries

There are a few main ways dictionaries are used:





initialize a dict

Dicts are marked by curly braces. Keys and values are separated with colons.


initialize a dict

mydict = {}                        # empty dict

mydict = {'a':1, 'b':2, 'c':3}     # dict with str keys and int values




add a key/value pair to a dict

We use subscript syntax to assign a value to a key.


mydict = {'a':1, 'b':2, 'c':3}

mydict['d'] = 4                 # setting a new key and value

print(mydict)                   # {'a': 1, 'c': 3, 'b': 2, 'd': 4}




retrieve a value from a dict using a key

We also use subscript syntax to retrieve a value.


mydict = {'a':1, 'b':2, 'c':3, 'd': 4}

dval = mydict['d']                 # value for 'd' is 4

xxx = mydict['c']                  # value for 'c' is 3

You might notice that this subscripting is very close in syntax to list subscripting. The only difference is that instead of an integer index we are using the dict key (most often a string).





the KeyError exception

This exception is raised when we request a key that does not exist in the dict.


mydict = {'a': 1, 'b': 2, 'c': 3}

val = mydict['d']       # KeyError:  'd'

Like the IndexError exception, which is raised if we ask for a list item that doesn't exist, KeyError is raised if we ask for a dict key that doesn't exist.





check for key membership

If we're not sure whether a key is in the dict, before we subscript we can check to confirm.


mydict = {'a': 1, 'b': 2, 'c': 3}

if 'a' in mydict:
    print("'a' is a key in mydict")




[pr]