Access to a member of a dictionary in one dictionary

I am trying to do something like this:

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

It seems to Kant that the syntax is correct, is there a way to do this without using multiple dictionaries or defining them elsewhere?

+4
source share
2 answers

You cannot access _dict when defining it. Python first evaluates the literal {...} dict before assigning _dict . In other words, when evaluating the expression {...} dict literal _dict is not yet defined, and therefore it is not possible to access.

Do this instead:

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

You can either assign from the same var:

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

Or do it with two statements (still the same dict):

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

If you can clarify what you are trying to achieve, there may be a more elegant solution that can be found. Often, when you need to determine the value of a dict based on another, this is because the values ​​are dynamically determined using a parameterized operation. In such cases, you can sometimes use an expression for an expression / list generator. For instance.

 >>> dict((v, 1234+i) for i, v in enumerate(("foo", "bar"))) {'foo': 1234, 'bar': 1235} 
+9
source

Source: https://habr.com/ru/post/1436105/


All Articles