Reputation: 95
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:
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
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
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
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