Dictionaries of Lists

Tony Meyer t-meyer at ihug.co.nz
Tue Mar 8 00:26:22 EST 2005


> I'd like to associate certain lists with keywords, and
> retrieve them.  But this is not possible as lists are
> not hashable.

A dictionary's values don't have to be hashable, so if the keywords are the
keys in the dictionary, this would work.

>>> d = {}
>>> d['key1'] = [1,2,3]
>>> d['key2'] = [4,5,6]
>>> d
{'key2': [4, 5, 6], 'key1': [1, 2, 3]}

> I don't mind making my lists immutable.  Is there a way
> to tupelize them?

>>> l = [1,2,3,4]
>>> tuple(l)
(1, 2, 3, 4)
>>> list(tuple(l))
[1, 2, 3, 4]

> I tried mydict[mykey]=([a for a in list]) but it
> didn't seem to work.

[a for a in list] (or a[:]) makes a copy of a list.  Putting parentheses
around a list does absolutely nothing.  You then assign the copied list to
the 'mykey' index in the dictionary.

=Tony.Meyer




More information about the Python-list mailing list