I would like to define a dictionary as follows:
dict = {
Player: $key.Name + " takes some action"
}
Is there a syntax that would allow me to do this?
I want to avoid using Player
twice. For example, if I want to replace Player
with AdvancedPlayer
, I have two references to replace.
Dictionary comprehensions may help.
>>> players = ["Mark", "Jack", "John"]
>>> player_dict = {k: k + " takes some action" for k in players}
>>> player_dict
{'John': 'John takes some action', 'Jack': 'Jack takes some action', 'Mark': 'Mark takes some action'}
They take the form {
key:
value for
variable in
iterable}
The question to me means something different than what the code suggests, that is: you want to reference the dictionary key in its value in the same context in which you create the dictionary.
You can do that with the walrus (:=
) operator (from Python 3.8):
d = {
(k := "key"): f"Value + {k}"
}
print(d)
{'key': 'Value + key'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With