Lo-Phi
Lo-Phi

Reputation: 95

How can I randomly select between a structure that initializes variables?

I am attempting to assign strings to variables, and then randomly select from those variables.

The problem is that I can't find a way to:

  1. Randomly select from a class, or some other structure that allows for me to initialize the variables within the structure, or
  2. Choose from a list of variables, where I am not required to type information redundantly

Ideally, I would like something like this:

class Websites:
    google = "https://google.com"
    twitter = "https://twitter.com"
    instagram = "https://instagram.com"

and then be able to choose from those:

print(random.choice(Websites))

I've also tried creating a pseudo-switch statement:

from project.config import Websites

def switch_website(random_site):
    _ = Websites

    return {
         1: _.google
         2: _.twitter,
         3: _.instagram
    }[random_site]

But this requires me to put the variable name in both the class and the dictionary, which is problematic because the final list will be quite large, and will need to be amended with extra sites later on.

My apologies if I use incorrect terminology, I started using Python yesterday.

Thanks for the help!

Upvotes: 2

Views: 75

Answers (3)

Reedinationer
Reedinationer

Reputation: 5774

It seems to me you are trying to find a dictionary. These let you store key-value pairs like your example (a class seems inappropriate for this for sure, maybe you are used to defining everything in one like in Java or something). You could accomplish your example like this (there are other ways too I'm sure):

import random

websites = {
    'google': "https://google.com",
    'twitter': "https://twitter.com",
    'instagram': "https://instagram.com"
}

website_name_list = list(websites.keys())
print(website_name_list)
random_website_name = random.choice(website_name_list)
print(random_website_name)
corresponding_url = websites[random_website_name]
print(corresponding_url)

Where an example output would be

['twitter', 'google', 'instagram']
google
https://google.com

Upvotes: 0

martbln
martbln

Reputation: 314

If you need just get random from several values, create list of these values and use random choice.

import random

google = "https://google.com"
twitter = "https://twitter.com"
instagram = "https://instagram.com"

site_list = [google, twitter, instagram]

print(random.choice(site_list))

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 993243

You can use a dictionary for this:

import random

Websites = {
    "google": "https://google.com",
    "twitter": "https://twitter.com",
    "instagram": "https://instagram.com",
}

print(random.choice(list(Websites.items())))

If you want just the URL part, use values() instead of items():

print(random.choice(list(Websites.values())))

Upvotes: 4

Related Questions