Accessing Dictionary values from within the Dictionary

Robin Munn rmunn at pobox.com
Sun Nov 17 02:44:55 EST 2002


Kuros <kuros at pgtv.net> wrote:
> Hi again,
> 
> I have created a dictionary, like so:
> 
> dict = {var1 : 0, var 2: 0}
> 
> Now, i want the third key/value pair to equal the total values of var1 and 
> var2. I tried to do it this way:
> 
> dict = {var1 : 1, var 2 : 2, var3 : dict[var1] + dict[var2]}
> 
> But I get an invalid syntax error.
> 
> Could someone help me out with this?

Others have posted code that will work, so I will limit myself to one
code-related comment: don't use dict as a variable name, *ever*. Nor
int, str, list, tuple... Those are not reserved words, so Python lets
you use them as variable names -- but by doing so, you're shadowing a
built-in function, which is a Bad Idea and will cause much confusion
(and subtle bugs) later on when you're not expecting problems.

Now, the concept you need to understand here is precisely how assignment
works: *first* the right-hand side is evaluated, and only *after* that
does the result get bound to the name on the left-hand side. So in your
example, at the time that "dict[var1]" and "dict[var2]" get evaluated,
there is no dictionary named dict and so these expressions fail. But
the following code will work:

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

When the RHS of the second statement is evaluated, the name the_dict is
already bound to a dictionary object that has keys 'var1' and 'var2'.
(BTW, make *sure* you understand the difference between "dict[var1]" and
"dict['var1']"! If you don't understand the difference between those two
expressions, you *will* have problems.) So the expression
"the_dict['var1'] + the_dict['var2']" works and evaluates to 3; then 3
is stored in the_dict['var3']. Note that this does *not* work like a
spreadsheet: if you later change the_dict['var1'], the_dict['var3'] will
*not* be recomputed.

Hope this helps you understand this better.

-- 
Robin Munn <rmunn at pobox.com>
http://www.rmunn.com/
PGP key ID: 0x6AFB6838    50FF 2478 CFFB 081A 8338  54F7 845D ACFD 6AFB 6838



More information about the Python-list mailing list