Win98 PySol/Python Problems II

Matthew Dixon Cowles matt at mondoinfo.com
Mon Dec 3 12:52:39 EST 2001


On Mon, 03 Dec 2001 15:42:42 GMT, Bill Melcher <wpmelcher at snet.net> wrote:

Dear Bill,

>Hi Guys,

Hi!

>Python - So I get the book and try a little simple stuff. Whoops!

Nobody expects the Spanish Inquisition!

>PythonWin 2.1.1 (#20, Jul 26 2001, 11:38:51) [MSC 32 bit (Intel)] on win32.
>Portions Copyright 1994-2001 Mark Hammond (MarkH at ActiveState.com) - see
>'Help/About PythonWin' for further copyright information.
>>>> import os
>>>> os.environ.keys()
>['TMP', 'INCLUDE', 'PATH', 'BKOFFICE', 'INETSDK', 'TEMP', 'WINBOOTDIR',
>'BASEMAKE', 'MSSDK', 'BLASTER', 'LIB', 'COMSPEC', 'PROMPT', 'CMDLINE',
>'MSTOOLS', 'WINDIR', 'DXSDKROOT']
>>>> os.environ.keys('PATH')
>Traceback (most recent call last):
>  File "<interactive input>", line 1, in ?
>TypeError: keys() takes exactly 1 argument (2 given)
>>>> os.environ.keys['PATH']
>Traceback (most recent call last):
>  File "<interactive input>", line 1, in ?
>TypeError: unsubscriptable object
>>>>

os.environ is a dictionary. That is, a thing that's subscriptable by
strings and various other things. As with all dictionaries in Python,
the subscripting is done with square brackets:

>>> os.environ["HOME"]
'/home/matt'

The subscripts are generally called keys and the things returned are
generally called values in Python. This dictionary has strings for
both its values and its keys but dictionaries aren't limited to using
strings.

When you create a dictionary from scratch in your program, the syntax
uses curly brackets rather than square ones. (I don't know the reason
for the inconsistency and it quickly stopped bothering me.) Here's an
example:

>>> d={"a":2}
>>> d["a"]
2
>>> d["b"]=3
>>> d
{'b': 3, 'a': 2}

Sometimes it's useful to know what keys have been assigned to. You
can do that with a dictionary's keys() method:

>>> d.keys()
['b', 'a']

Note that the keys aren't returned in a dictionary, it's a list. There's
an analogous method for a dictionary's values:

>>> d.values()
[3, 2]

So what you really wanted in the first place is probably something like:

>>> os.environ["PATH"]

Here's the explanation for the odd error message you got. In Python,
functions can be passed around and stored in variables:

>>> def a():
...   print "wibble"
... 
>>> a()
wibble
>>> b=a
>>> b()
wibble

If I can call a by saying a(), then a is the name for the relevant
code. The same thing is true for methods. dict.keys() gets me the
dict's keys, and dict.keys is the code that does it:

>>> d.keys()
['b', 'a']
>>> d.keys
<built-in method keys of dictionary object at 0x8117a7c>

Up above you wanted to subscript the dict but subscripted the keys
method so Python complained that it couldn't subscript the code.

Regards,
Matt



More information about the Python-list mailing list