Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
196 views
in Technique[技术] by (71.8m points)

python - Can I use information of a dict key to define another key of the same dict?

What I'd like to do is the following:

test_dict = dict(value = 1,
                 property = properties_list[value-1]
                )

Naturally, I couldn't do it this way, since it throws me an error saying that name 'value' is not defined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could do it by using an assignment expression (aka “the walrus operator”) which were introduced in Python 3.8.

properties_list = [42, 13]

test_dict = dict(value=(_:=1), property=properties_list[_-1])

print(test_dict)  # -> {'value': 1, 'property': 42}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...