Accessing Dictionary values from within the Dictionary

Alex Martelli aleax at aleax.it
Fri Nov 15 08:08:26 EST 2002


Kuros 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?

The main help I can give you: copy and paste the example you say
is failing -- make it as tiny as possible as long as it still fails.
When you try to teport an error WITHOUT copy and paste, it's just
too likely that what you end up saying is just false, thus wasting
the time of anybody who's trying to help.

E.g, in this case:

>>> dict = {var1 : 0, var 2: 0}
  File "<stdin>", line 1
    dict = {var1 : 0, var 2: 0}
                          ^
SyntaxError: invalid syntax
>>>

So you CANNOT possibly, as you claim, have created a dictionary
as you say -- that weird extra space in 'var 2' makes your
assertion impossible.


Another piece of advice: don't name your variables dict, list,
tuple, file, int, str, and by other built-in type names used by
Python.  It's not illegal, but it makes for a LOT of confusion
and needless bugs.  Call them adict, somelist, mytuple, thefile,
etc, if it's just TOO hard to think of a useful name...


Alex




More information about the Python-list mailing list