Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a dictionary member within the same dictionary

I am trying to do something like this:

_dict = {"foo" : 1234,
         "bar" : _dict["foo"] + 1}

Cant seem to get the syntax correct, is there a way to acomplish this without using multiple dictionaries, or defining them elsewhere?

like image 824
xceph Avatar asked Nov 29 '22 02:11

xceph


1 Answers

You cannot access _dict while defining it. Python first evaluates the {...} dict literal before assigning it to _dict. In other words, while evaluating the {...} dict literal statement, _dict is not yet defined and thus cannot be accessed.

Do this instead:

_dict = {"foo" : 1234}
_dict["bar"] = _dict["foo"] + 1
like image 107
Martijn Pieters Avatar answered Dec 05 '22 11:12

Martijn Pieters