[Tutor] Using a dict value in the same dict

Peter Otten __peter__ at web.de
Tue Jul 5 19:04:24 CEST 2011


Válas Péter wrote:

> I have a dictionary with the keys 'a' and 'b'. It is not in a class. (I
> know that everything is in a class, but not explicitly.)
> May I use the value of 'a' when defining the value of 'b'? If so, what is
> the syntax?

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

If you want the value of "b" updated whenever d["a"] changes, i. e. that the 
dict values behave like spreadsheet cells, that is not possible with a 
standard python dictionary. 
There is a recipe by Raymond Hettinger with a simple implementation of that 
behaviour at

http://code.activestate.com/recipes/355045-spreadsheet/

As it uses eval() it is OK for private use, but you shouldn't allow a 
potentially malicious user to run it.




More information about the Tutor mailing list