[PyKDE] Can I use QString as key in Python dictionary?
Gerard Vermeulen
gerard.vermeulen at grenoble.cnrs.fr
Thu Jun 2 08:54:06 BST 2005
On Thu, 02 Jun 2005 08:08:34 +0200
Torsten Marek <shlomme at gmx.net> wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Sebastian Kügler schrieb:
> > On Thursday 02 June 2005 04:10, Matej Cepl wrote:
> >
> >>I have this simple dialog in PyQt, but whenever I press any item in
> >>the list (or click OK), I get this error:
> >>
> >> chelcicky:pycatsel$ ./pycatsel
> >> Traceback (most recent call last):
> >> File
> >>"/home/matej/archiv/programky/vim-qadas/pycatsel/selectCode.py",\
> >>line 148, in Quit
> >> note = unicode(self.dictCategories[key])
> >> KeyError: <__main__.qt.QString object at 0xb7e12c5c>
> >> chelcicky:pycatsel$
> >>
> >>Does anybody have any idea, what's wrong? Can I use QString as a key
> >>in Python dictionary (both key and dict's values are QStrings)?
> >
> >
> >>>>from qt import *
> >>>>QString("foo") is QString("foo")
> >
> > False
> >
> > As you can see these two QString are different objects, so there's
> > actually no such key.
> >
> >
> >>>>k = QString("bla")
> >>>>mydict = {QString("bla"):"foobar"}
> >>>>mydict[k]
> >
> > Traceback (most recent call last):
> > File "<stdin>", line 1, in ?
> > KeyError: <qt.QString object at 0xb7df350c>
> >
> > As you can see, it yields a KeyError because k is actually no key in
> > mydict. However, you can use a QString as a key, but you have to use
> > exactly that reference (not a *similar* one):
> >
> >
> >>>>k = QString("bla")
> >>>>mydict = {k:"foobar"}
> >>>>mydict[k]
> >
> > 'foobar'
>
> One could think about changing the QString implementation of __hash__ to use the
> strings's contents only. This shouldn't be too difficult (although I didn't try
> it out, so I'm probably wrong.).
>
A Python string is immutable and a QString is mutable.
You'll may get undefined behaviour if you change a QString key while
manipulating a dictionary containing that QString key.
Gerard
More information about the PyQt
mailing list