Emlingur
Emlingur

Reputation: 163

Value set according to another value in the same dictionary, python

How would I solve this issue?

d = {
'a':3, 
'b':(d['a']*3)
}

print(d)

results in an error because I try to set the value of 'b' using the name of the dictionary, and apparently python does not like that. How would I get around this?

Also:

l = [[2], [(l[0][0]*2)]]

print(l)

has the same issue.

Upvotes: 2

Views: 58

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77912

Given how assignment works - the RHS expression is eval'd first, and only then is the resulting object bound to the LHS -, that was to be expected : you cannot reference a name that has not been yet created in the current scope.

The solutions are either to use an intermediate variable for the value you want to reuse, as explained in lambo's answer, or to first build the dict (or list or whatever) with the first key or index/value pair then build the other, ie:

d = {"a", 3}
d["b"] = d["a"] * 3

Upvotes: 4

gtlambert
gtlambert

Reputation: 11961

Assign the values to variables first:

x = 3
d = {'a': x, 'b': x*3}

y = 2
l = [[y], [y*2]]

Upvotes: 2

Related Questions