How does one return a random number from a dictionary every time a key is called?
<p>I am trying to create a weapon that provides random damage. I am doing so using an item database in the form</p>

<pre><code>itemsList = {
1: {"name": "Padded Armor",  "armor": 1,  "value": 5, "class": "Light"},
2: {"name": "Leather Armor",  "armor": 2,  "value": 10, "class": "Light"},
....
19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"},
20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"},
21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"},
22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"}
}
</code></pre>

<p>Every time I attempt to call <code>"damage"</code> it just returns the same result. I understand that this is because the random number is generated one and then saved to that dictionary key. </p>

<p>How would I go about generating a random number every time damage is called?</p>

<p>You would store a function that generates a random number, not the random number itself, in the dictionary. (By the way, if your dictionary's keys are just sequential integers, consider using a list instead.) </p>

<pre><code>from random import randrange    
itemsList = [
  {"name": "Padded Armor",  "armor": 1,  "value": 5, "class": "Light"},
  {"name": "Leather Armor",  "armor": 2,  "value": 10, "class": "Light"},
  ....
  {"name": "Dagger", "damage": lambda: randrange(1, 4), "value": 2, "Type": "Dagger"},
  {"name": "Dagger + 1", "damage": lambda: randrange(1, 4) + 1, "value": 200, "Type": "Dagger"},
  {"name": "Dagger + 2", "damage": lambda: randrange(1, 4) + 2, "value": 750, "Type": "Dagger"},
  {"name": "Dagger + 3", "damage": lambda: randrange(1, 4) + 3, "value": 2000, "Type": "Dagger"}
]
</code></pre>

<p>Then, you simply call the function to get an actual damage roll:</p>

<pre><code># Roll damage for a dagger + 3
damage = itemsList[22]["damage"]()
</code></pre>

python dictionary random properties python-descriptors