[Tutor] Hash of Lists? [Dictionaries]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue Oct 22 23:57:01 2002


On Tue, 22 Oct 2002, Sean 'Shaleh' Perry wrote:

> On Tuesday 22 October 2002 17:22, learning_python@turbonet.com wrote:
>
> > I've been perusing the archives for several days, but I haven't come
> > across Python applicable info on what Perl users apparently call a
> > "hash of lists."
> >
> > If I understand correctly, this functionality is replicated in Python
> > through "dictionaries," which are described as being implemented as
> > "resizable hash tables" with "immutable keys."

Hello!

Yes, the concept of a "hash" in Perl directly maps to the "dictionary"
concept in Python.  *grin*


> d = {}
>
> d['chargers'] = [1,0,1,0,1] # list of wins/losses with 1 meaning a win
> d['raiders'] = [1,1,1,1,0]
> d['panthers'] = [0,0,0,0,0]

This 'd' is a dictionary (hashtable) that allows us to associate team
names with their win-loss records.  The mapped values can be any Python
object, including the win-loss lists that Sean uses here.



Dictionaries can be really useful!  We can do simple things, like
associate file extensions to their descriptions:

###
>> langs = {}
>>> langs['.c'] = 'C'
>>> langs['.py'] = 'Python'
>>> langs['.pl'] = 'Perl'
>>> langs['.scm'] = 'Scheme'
>>> langs['.sml'] = 'Standard ML'
>>>
>>> langs
{'.py': 'Python',
 '.pl': 'Perl',
 '.sml': 'Standard ML',
 '.c': 'C',
 '.scm':  'Scheme'}
>>>
>>> langs['.c']
'C'
###


If you're familiar with Perl, think of all Python values as "scalars".
In Python, it's a snap to have a dictionary that maps strings to lists:

###
>>> hellos = {} hellos['python'] = ''' ###
... print "hello world!" ... '''.strip().split('\n')
>>>
>>> hellos['C'] = '''
... int main(void) {
...     printf("hello world!\n");
... }
... '''.strip().split('\n')
>>>
>>> hellos['scm'] = '''
... (begin (display "hello world!")###
...  (newline))
... '''.strip().split('\n')
>>>
>>> hellos
{
 'python': ['print "hello world!"'],
 'scm':    ['(begin (display "hello world!")',
            '       (newline))'],
 'C':      ['int main(void) {',
            '    printf("hello world!', '");',
            '}']
}
###

[I adulterated some of the output to make it look nicer as an email
message.  Hope I didn't introduce more typos...]



One neat thing about Python is that the keys that we can use for our
dictionaries don't have to be strings or integers: they can also be
tuples!  This is actually quite useful at times!  For example, we can
represent a sparse matrix with ease if we use tuples as the keys:


###
>>> def print_matrix(matrix, i, j):
...    for y in range(i-1, -1, -1):
...        for x in range(j):
...            if matrix.has_key((x, y)):
...                print matrix[x,y],
...            else:
...                print '0',
...        print
...
>>> def make_ones(n):
...    matrix = {}
...    for i in range(n):
...        matrix[(i, i)] = 1
...    return matrix
...
>>> m = make_ones(5)
>>> print_matrix(m, 5, 5)
0 0 0 0 1
0 0 0 1 0
0 0 1 0 0
0 1 0 0 0
1 0 0 0 0
###


I hope this helps make the dictionary concept more concrete for you.
Good luck!