[Tutor] Hash of Lists?

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue Oct 22 21:02:01 2002


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 ac=
ross
> 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."
>
> I'm looking for a newbie-level tutorial of these concepts, hopefully wi=
th
> example code.  I've googled and googled, to no avail.
>
> Can anyone point me towards a relevant URL?
>

d =3D {}

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

etc.

They key must be immutable (strings are) the data can be anything.

for team in d.keys():
    wins =3D reduce(operator.add, d[team])
    print '%s has won %d games' % (team, wins)

or perhaps this example cribbed from the thread "sorting into lists".

> Hey everyone,
>
> Let's say I've got a list like the following:
>
> l =3D [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4]
>
> I'm trying to figure out a good way to turn this list into
>
> [[1, 1, 1], [2, 2], [3, 3, 3, 3], [4, 4]]

Hi Tim,

Is this grouping identical elements?  Do we have to worry about what
happens when the list isn't in order?  More information on the problem
might allow us to write more appropriate programs.


Here's one approach that uses dictionaries:

###
def formGroups(L):
    groups =3D {}
    for item in L:
        groups.setdefault(item, []).append(item) # **import line!!!**
    return groups.values()
###

explanation:
setdefaults() is a method on dictionaries which returns the value if the =
key=20
exists of inserts a default value into the dictionary.  So if item is in =
the=20
dictionary groups the list it points to is returns and the lists append()=
=20
method is called which adds another item to the list.  Otherwise an empty=
=20
list is put in the dictionary (that []) and then item is appended.

if you wrote this by hand you'd get

if not groups.has_key(item):
    groups[item] =3D []
groups[item].append(item)

Hope this helps you on the path to enlightenment.  if not, please let us =
have=20
a more specific question.