Accessing Dictionary values from within the Dictionary

Mel Wilson mwilson at the-wire.com
Fri Nov 15 10:10:39 EST 2002


In article <mailman.1037366016.17160.python-list at python.org>,
pinard at iro.umontreal.ca (=?iso-8859-1?q?Fran=E7ois?= Pinard) wrote:
>Probably this would work for you:
>
>    dict = {'var1': 1, 'var2': 2, 'var3': dict['var1'] + dict['var2']}

I doubt it:


Python 2.1.3 (#35, Apr  8 2002, 17:47:50) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
>>> dict = {'var1': 1, 'var2': 2, 'var3': dict['var1'] + dict['var2']}
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'dict' is not defined
>>>


   If the original poster had said *which* syntax error..

To the original poster:

   Consider just

dict = {'var1':1, 'var2':2}

   First the Python interpreter builds a dictionary using
the expression `{'var1':1, 'var2':2}`

   If this succeeds, then the interpreter associates the
dictionary object with the name `dict` in one of its own
symbol dictionaries.  So when you try to refer to the `dict`
dictionary within the expression that builds the dictionary
that later will be called `dict`.. you find there is no such
thing.

.. if you're lucky.  If there's a different object called
`dict` at the time your statement is executed, that will be
used instead.  That had better be what you want.

   It goes beyond Python .. most common computer languages
.. certainly the FORTRAN- or Algol-flavoured ones ,, work
this way.

        Regards.        Mel.



More information about the Python-list mailing list