[Tutor] dictionary values in strings
Max Noel
maxnoel_fr at yahoo.fr
Thu May 19 22:47:50 CEST 2005
On May 19, 2005, at 20:49, William O'Higgins wrote:
> I am trying to discover the syntax for call on a dictionary of
> lists by
> key and index.
>
> The data structure looks like this:
>
> dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\
> 'key3':['li1'li2,'li3','']}
>
> The keys are passed to a function as arguments, and I want the
> value of
> the specified list index. This is what I *thought* it would look
> like:
>
> dol.key(argument)[0] # would return li1 when argument equals key1
>
> But that's wrong. The error I get is this:
> AttributeError: 'dict' object has no attribute 'key'
>
> I don't know how to interpret that error (well, I know I screwed
> up, but
> ... :-) Thanks.
As the error message implies, dictionaries don't have a key
attribute. They do, however, have a keys() method:
>>> a = {'foo': 1, 'bar': 2}
>>> a.keys()
['foo', 'bar']
And they also have the has_key() method, which can be used to
test for the presence of a key in a dict:
>>> a.has_key('foo')
True
>>> a.has_key('baz')
False
What you are looking for can be achieved like this:
>>> dol = {'key1':['li1','li2','li3'],'key2':['li1','li2','li3'],\
... 'key3':['li1', 'li2','li3','']}
>>> dol['key1'][0]
'li1'
Hope that helps,
-- Max
maxnoel_fr at yahoo dot fr -- ICQ #85274019
"Look at you hacker... A pathetic creature of meat and bone, panting
and sweating as you run through my corridors... How can you challenge
a perfect, immortal machine?"
More information about the Tutor
mailing list