Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reference the key in the value when creating a dictionary?

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.

like image 612
Shagglez Avatar asked Sep 15 '25 02:09

Shagglez


2 Answers

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}

like image 142
Utaal Avatar answered Sep 17 '25 17:09

Utaal


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'}
like image 30
user582175 Avatar answered Sep 17 '25 17:09

user582175