Accessing Dictionary values from within the Dictionary

François Pinard pinard at iro.umontreal.ca
Fri Nov 15 08:13:59 EST 2002


[Kuros]

> I have created a dictionary, like so:
> dict = {var1 : 0, var 2: 0}

Did you mean?

    dict = {'var1': 0, 'var2': 0}

Be careful, you probably did not intend a space between `var' and `2'.

> dict = {var1 : 1, var 2 : 2, var3 : dict[var1] + dict[var2]}
> But I get an invalid syntax error.

Probably this would work for you:

    dict = {'var1': 1, 'var2': 2, 'var3': dict['var1'] + dict['var2']}

But you know, you may add to a dictionary without rebuilding whole.
After having done:

    dict = {'var1': 0, 'var2': 0}

you may well merely complete it by doing only:

    dict['var3'] = dict['var1'] + dict['var2']

> Could someone help me out with this?

The best advice I think I could give you is developping the habit of
re-reading your code very carefully.  Hmph!  I hope I do not myself have
too many mistakes in this reply :-).

Programming languages are not much forgiving, you have to be extremely
precise in what you write.  It should also be worth going through the
Python tutorial very patiently, repeating all the exercises by yourself,
playing around them, mastering everything written in there.  You might
also choose to buy good books on Python programming, there are many, and
accepting to invest time for scrutinising them carefully.  These should
help you getting acquainted with the art of programming!

-- 
François Pinard   http://www.iro.umontreal.ca/~pinard




More information about the Python-list mailing list