Random dictionary pick?

Viewed 48

I am pretty newbie to python, still learning. Here i faced a problem i can't figure out how to solve yet.

import random
materials = ["wood", "stone", "iron"]

wood = {
    "name": "wood",
    "weight": 50,
    "quality": 1
}

stone = {
    "name": "stone",
    "weight": 80,
    "quality": 2
}

iron = {
    "name": "iron",
    "weight": 110,
    "quality": 3
}

r = random.choice(materials)

Basically what i wanted to do is to print a specific dictionary depends from the r - random pick. Any tips on how to do that correctly?

2 Answers

You should use object type instead of string, from

materials = ["wood", "stone", "iron"]

to

materials = [wood, stone, iron]

And you should also call this after assign those object.

I'd say just use a list of dictionaries. The random pick will be the dictionary in that case:

import random

materials = [{
    "name": "wood",
    "weight": 50,
    "quality": 1
}, {
    "name": "stone",
    "weight": 80,
    "quality": 2
}, {
    "name": "iron",
    "weight": 110,
    "quality": 3
}]

r = random.choice(materials)

print(r)
Related