How to use list as key of dictionary?

Steven D'Aprano steve at
Tue Nov 6 17:00:15 CET 2007

On Tue, 06 Nov 2007 11:25:29 +0000, Duncan Booth wrote:

> Steven D'Aprano <steve at> wrote:
>> Not quite, because that will also convert strings to tuples, which may
>> not be what you want for a general solution.
> I take it you didn't actually try the original code then. 

No I didn't.

> Converting strings to tuples is not something it did.

Ah yes, you're right. The old "single characters are sequences too" 
gotcha bites again.

>> That works for all data types I've tried, and it insures that the keys
>> it makes from different types are distinguishable:
>> e.g.
>> make_dict_key([(1, 2), (3, 4)]) != make_dict_key({1: 2, 3: 4})
> Really? It seems to me to be quite easy to get a clash:
>>>> make_dict_key([])
> (<type 'list'>,)
>>>> make_dict_key((list,))
> (<type 'list'>,)

I should have said "tries to insure". It isn't strictly possible to avoid 
all clashes, even in principle. For any mutable object M, if make_dict_key
(M) returns a key K, then make_dict_key(K) will also return K. 

However, the clashes are for unusual containers with a type as the first 
element, instead of "usual" containers containing lists, tuples, strings, 
etc. Unless you deal with tuples with the first item being a type, you 
shouldn't come across any clashes. 

Also: nice work on supporting recursive data structures, thanks.


More information about the Python-list mailing list