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 may find it reduces the repetition in your code to store just the damage weighting (still called <code>damage</code> in my code) in your dictionary and have a separate function to calculate the actual damage. e.g.</p>

<pre><code>from random import randint

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" : 0, "value": 2, "Type": "Dagger"},
20: {"name": "Dagger + 1", "damage" : 1, "value": 200, "Type": "Dagger"},
21: {"name": "Dagger + 2", "damage" : 2, "value": 750, "Type": "Dagger"},
22: {"name": "Dagger + 3", "damage" : 3, "value": 2000, "Type": "Dagger"}
}

def getdamage(item):
    return randint(1, 4) + item['damage']

# test code
for i in range(20):

    item = randint(19, 21)
    damage = getdamage(itemsList[item])
    print("I used item %d and made damage %d" % (item, damage))
</code></pre>

<p>Now your random function is only in one place and if you decide to change it later it will be less work.</p>

<p>One thing I don't get though is why have the armour and weapons in one list? You could pass the index of some armour to the damage function and get an error.</p>

python dictionary random properties python-descriptors