esoteric question about dict keys (Re: age of Python programmers)

A

Alexis Roda

This is my first message to the list, so I'll present myself and add my
contribution to the "age of python programmes" thread.

My name is Alexis Roda, I'm 36 - 7/365 years old, I started programming
with python two years ago, mainly because I started playing with zope.
At first I was a reluctant Perl converted, although initially I hated
python (well, I hated zope wich make me hate python) now I'm in love
with both python and zope. I started programming at 15 with a Casio
calculator (a kind of assembler), then an Amstrad CPC464 (Basic), a
Macintosh Plus (Pascal, C, Lisp, assembler) and finally come to the
PC/Linux world (assembler, C, C++, Perl, bash scripting, elisp and python).

Now the question. In "normal" dicts its not possible to use dictionaries
(nor other kinds of mutable objects) as keys, if I undersand correctly
this is a technical requirement. If I write my own dictionary-like
object, on wich the mutability of the keys is not a technical issue, is
considered blasphemous the use of dicts as keys? For example, querying
an SQL table can be partially modelled as a dictionary access:

table[pkey_value] gives a record for this primary key

table[{'somefield':somevalue}] returns all the records where
somefield=somevalue

or is preferable to define a query() method for these uses and restrict
__getitem__ to mutable objects for the sake of consistency?




TIA
--
////
(@ @)
----------------------------oOO----(_)----OOo--------------------------
<> Ojo por ojo y el mundo acabara ciego
/\ Alexis Roda - Universitat Rovira i Virgili - Reus, Tarragona (Spain)
-----------------------------------------------------------------------
 
R

Reinhold Birkenfeld

Mel said:
As I understand it, you can use any object as a key if
you give it a __hash__ method and an __eq__ or __cmp__
method.

You can, after all, use dicts as dict keys if you create your own
subclass of dict:

class hashdict(dict):
def __hash__(self):
return id(self)

x = hashdict()
testdic = {x : "test"}

But in order to retrieve the "test" value, you would need to index the
testdic with exactly the same instance of the hashdict. And that's why
dictionaries are unhashable.

Reinhold
 
G

Greg Ewing

No, not at all. If the algorithm you use for looking
up your mapping doesn't have any problem with mutability,
then using a dict (or indeed any comparable object)
as a key is fine.
 

Members online

No members online now.

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top