Using Random Choice From Dictionary to Make An Image Appear? - python

Some preface:
I am using trinket. I am trying to make a tarot reading program for class. Using a nested dictionary, I have the name of each card, the facing of each card, and then a short (3-4 words) reading that is then outputted as a template for the user.
Example of nested dictionary:
card_names = {
"The Fool" : {"Up": "new beginnings, pleasure, & opportunity" , "Down" : "indecision, hesitation, & bad choices" },
"The Magician" : {"Up" : "creativity, self-confidence, & skill" , "Down" : "delay, insecurity, & lack of self-confidence" }
I then use the random.choice function to generate both a card and it's facing, like so:
card = random.choice(list(cards.card_names))
facing = random.choice(list(cards.card_names[card]))
Then it outputs a reading based on answers users put in & the randomly generated card:
print(__main__.answer_list[0] + ", your past was represented by " + random.choice(list(cards.card_names)) + ", which is facing " + random.choice(list(cards.card_names[card])) + "." " This tells me that your past relationships brought " + (cards.card_names[card][facing]) + " into your life.")
it ends up looking something like in output:
"
Em, your past was represented by The Chariot, which is facing Up. This tells me that your past relationships brought misery, greedy, & money into your life.
Now that I have the program actually working, I want to make it so that the random.choice cards that are chosen will actually show to the user, using files such as "tarot-fool.jpeg".
I made a second dictionary that looked like this:
card_images = {"The Fool": "tarot-fool.jpeg", "The Magician": "tarot-magician.jpeg"}
I hoped that I could have the program take the random.choice generated card from the card_names dictionary , parse the second dictionary for matches, and then once it found the card with matching keys, it would output the value of the second dictionary card_images, and then use the screen.bgpic() function to show users the card while they read their tarot reading output.
I tried something similar to this:
namesset = set(card_names)
imageset = set(card_images)
for name in namesset.intersection(card_images):
print name, card_images[name]
I also tried
card = random.choice(list(cards.card_names))
facing = random.choice(list(cards.card_names[card]))
key = card
key2 = cardimages.key()
value = cardimages.value()
if key in key2:
print value
just to see if I could get the program to isolate the correct value from card_images before I start trying to get them to show on screen, but I am unable to get the program to isolate the randomly selected card, remember it, and then parse the second dictionary for just that value. The code above works, but outputs every single name of every single .jpeg.
Please help! I honestly think this is something a little too complex to be using trinket for, especially with the images component. I have some experience coding outside of it but this is for a class project that we HAVE to turn in with trinket so if someone could either help me out or just tell me if this is not achievable through trinket so I can change direction a bit, it would be much appreciated.
see above for what I've tried

Related

Extract info when JSON when key changes in Python

I'm quite new to Python so please excuse me if my terminology is not 100% accurate or if this is quite simple
I currently have the code:
import requests
POINTS = requests.get('https://api.torn.com/market/?selections=pointsmarket&key=jtauOcpEwz0W0V5M').json()
POINTSA = POINTS['pointsmarket']
print (POINTSA)
I want to print the cost of the very first key. However, the number for the first key will always change.
At the time of posting the first key is 9765126 as seen here:
https://imgur.com/VRi8Owe
So the line would be (I think):
POINTSA = POINTS['pointsmarket'][9765126]['cost']
However in 5 minutes time, the 9765126 key will change to something else. How do I get it to print the 1st cost entry regardless of the first key?
Hi you can try the following sample of getting the keys as a list then getting the first index
keys = list(POINTS['pointsmarket'].keys()) # Get all keys and convert to a list
POINTS['pointsmarket'][keys[0]]['cost']

How do I choose the position of the cursor when a user is inputting information in python?

Sorry If my code seems off, this is my first time asking here and I am somewhat new to python.
I want a user to give me the number of sets and reps for a workout.
Here is my code below:
print("Please enter the number of sets you would like to do followed by the number of reps. ")
sets, reps = input("Pushup- \n\t" + "Sets: " + "Reps: ").split()
So when I run this, naturally the cursor will be flashing at the end of "reps:" however what I want it to do is so that when I run it, the cursor will flash after "sets:" and when the user hits the space key, it will move all the way over to after "reps:".
I would recommend just having it as two inputs:
sets = input("Pushup-Sets: ")
reps = input("Pushup-Reps: ")
Is there a particular reason you need it done in one line?
Why don't you try doing something like this:
print("Please enter the number of sets you would like to do followed by the
number of reps.")
print("Pushup-")
sets = input("Sets:")
reps = input("Reps:")
It uses the return button instead of the spacebar, hope it helps!
As others have suggested, having it as two separate inputs will be much easier.
If you do want to make a text-based app which does it the way you've described, the library you're looking for is called "curses" (see: howto, reference).
However, it seems like a bit of an anachronism; for a quick app, separate inputs are much easier, and for a user-friendly app you'll probably want a graphical interface (or web) rather than a text-based one.

Is there a way to remove items from various lists based on conditional statements?

I am writing a program that will act as a photography idea-generator for New York photographers. The way it works now is quite simple, the code is utilizing the random.choice function to randomly pull items from lists, then the code prints them out in a way that forms a sentence in English as an end result.
My issue is I need to add some logic to this, as some results would not make sense for a photographer to do (at least in my opinion). In this example I am trying to remove 'Bracketed (HDR)' from the technique_list, IF "Portrait" happens to be randomly chosen when python chooses the theme item.
I have a feeling I am mis-using the .remove function within the conditional if statement. Is there a better way to do this? I have attached the pertinent parts of the code for examination.
I have tried technique_list.remove('Bracketed (HDR)') , as well as
del technique_list[0] , both as the response part of the if statement.
import random
print ("You should try taking a...")
#pool of items that the program will randomly choose..
theme_list = ['Cityscape','Peoplescape','Port-Scape', 'Portrait']
technique_list = ['Bracketed (HDR)','Wide Angle', 'Zoom','Long
Exposure','Fast Shutter','Daytime Long Expo','Timelapse']
#what we need here are conditional IF statements, that manipulate items
from various lists
#this bit of code determines the theme of a photo idea
theme_var = random.choice(theme_list)
for theme in theme_var:
if theme == 'Portrait':
technique_list.remove('Bracketed (HDR)')
print("",theme_var)
#this bit of code determines the technique of a photo idea
technique_var = random.choice(technique_list)
print("", technique_var)
print("picture, from")
#this line of code determines the location of a photo idea
location_var = random.choice(location_list)
print("", location_var)
This still remains one of the possible results of the code:
You should try taking a...
Portrait
Bracketed (HDR)
picture, from
34th Street
during
Sunrise
and then give it a
Black & White
edit in Lightroom!
[Finished in 0.2
As I said earlier, Portrait and Bracketed (HDR) should never be part of the same result, it doesn't make sense for this situation.
The issue (I think) is because you are iterating over the randomly chosen result not the list itself, you don't need the for loop that is.
theme_var = random.choice(theme_list)
if theme_var == 'Portrait':
technique_list.remove('Bracketed (HDR)')
print("",theme_var)
#this bit of code determines the technique of a photo idea
technique_var = random.choice(technique_list)
print("", technique_var)
print("picture, from")
#rest of the code
Should do it
I'd go with a dictionary of inappropriate techniques, a list comprehension, and top it off with an f-string:
import random
#pool of items that the program will randomly choose..
theme_list = ['Cityscape','Peoplescape','Port-Scape', 'Portrait']
technique_list = ['Bracketed (HDR)','Wide Angle', 'Zoom','Long Exposure','Fast
Shutter','Daytime Long Expo','Timelapse']
location_list = ['34th Street']
# dictionary of inappropriate techniques for given theme
d_inappropes = {'Cityscape': [],
'Port-Scape': [],
'Portrait': ['Bracketed (HDR)'],
'Peoplescape': ['Long Exposure', 'Timelapse', 'Daytime Long Expo']}
#this bit of code determines the theme of a photo idea
theme_var = random.choice(theme_list)
#this bit of code determines the technique of a photo idea
# list comprehension generates a new list with the inappropriate techniques removed,
# without affecting the original list
technique_var = random.choice([ti for ti in technique_list if ti not in d_inappropes[theme_var]])
#this line of code determines the location of a photo idea
location_var = random.choice(location_list)
# use f-stirngs to put the whole output in a single line to keep it managable
print(f"You should try taking a \n {theme_var} {technique_var} picture, \n from
{location_var}.")
if I may add and give more explanation to the answers
You want to delete "bracked (HDR)" IF potrait is selected. Don't use .remove as it will delete "bracked (HDR)" permanently and prevent other theme to use that technique. you can use dictionary of inappropriate technique as kingfischer suggested for that
random.choice outputted a single value from your list. you should not use for-loop with it as for-loop will iterate over the character/alphabets in the value outputted by random.choice
if I may give a feedback, the indentations in your code snippet are quite jumbled. Some lines that should have indentation, don't have it. I don't know.. maybe it is unintended and the problem is with my browser. if it was so, sorry!

Python 3 : Dictionary , adding multiple variables to a dictonary

I have a dictionary containing a profile. Every profile has a different amount of "abouts". For example Person 1 has as aboves: "lives there" "works there" "eats this" Person 2 has : "lives there".
All my profiles are in a for loop wich i didnt copy here. In this for loop i made a new loop where i want to get the range of the abouts and then create x variables containing the content of the [abouts] . Al this i want to write to my dictionary {friend}.
As output i want :
friend={"screenname":profilename,"id":profileid,"username":username,
"about 1" : lives in ,"about 2": works at , and so on untill al the abouts are found and written in the dict. }
Thanks a lot !
If i run this code he only puts the latest about in my dictionary.
for i in range(len(abouts)):
#print ("about"+str(i) +"=" +abouts[i])
friend={"screenname":profilename,"id":profileid,"username":username,
"about"+str(i):abouts[i]}
Why not insert a list into the dictionary key. Given that abouts is a list
friend={"screenname":profilename,"id":profileid,"username":username,
"about":abouts}
Since this is also an ordered collection, it would be much more efficient to fetch data using the index of about property
Update:
Since your desired output is
friend={"screenname":profilename,"id":profileid,"username":username,
"about 1" : lives in "} # and so on...
You can simplify your code to :
friend={"screenname":profilename,"id":profileid,"username":username} #create your dictionary first
for key, value in enumerate(abouts):
friend["about "+str(key)] = value
The problem with your code is your loop is the friend variable is being overwritten on every new loop. You you need to create your dictionary outside and update the field.
Though personally I would prefer using a List (my first example) instead as stated about as this is a much simpler approach and retrieving/displaying data is much easier.

match hex string with list indice

I'm building a de-identify tool. It replaces all names by other names.
We got a report that <name>Peter</name> met <name>Jane</name> yesterday. <name>Peter</name> is suspicious.
outpout :
We got a report that <name>Billy</name> met <name>Elsa</name> yesterday. <name>Billy</name> is suspicious.
It can be done on multiple documents, and one name is always replaced by the same counterpart, so you can still understand who the text is talking about. BUT, all documents have an ID, referring to the person this file is about (I'm working with files in a public service) and only documents with the same people ID will be de-identified the same way, with the same names. (the goal is to watch evolution and people's history) This is a security measure, such as when I hand over the tool to a third party, I don't hand over the key to my own documents with it.
So the same input, with a different ID, produces :
We got a report that <name>Henry</name> met <name>Alicia</name> yesterday. <name>Henry</name> is suspicious.
Right now, I'm hashing each name with the document ID as a salt, I convert the hash to an integer, then subtract the length of the name list until I can request a name with that integer as an indice. But I feel like there should be a quicker/more straightforward approach ?
It's really more of an algorithmic question, but if it's of any relevance I'm working with python 2.7 Please request more explanation if needed. Thank you !
I hope it's clearer this way รด_o Sorry when you are neck-deep in your code you forget others need a bigger picture to understand how you got there.
As #LutzHorn pointed out, you could just use a dict to map real names to false ones.
You could also just do something like:
existing_names = []
for nameocurrence in original_text:
if not nameoccurence.name in existing_names:
nameoccurence.id = len(existing_names)
existing_names.append(nameoccurence.name)
else:
nameoccurence.id = existing_names.index(nameoccurence.name)
for idx, _ in enumerate(existing_names):
existing_names[idx] = gimme_random_name()
Try using a dictionary of names.
import re
names = {"Peter": "Billy", "Jane": "Elsa"}
for name in re.findall("<name>([a-zA-Z]+)</name>", s):
s = re.sub("<name>" + name + "</name>", "<name>"+ names[name] + "</name>", s)
print(s)
Output:
'We got a report that <name>Billy</name> met <name>Elsa</name> yesterday. <name>Billy</name> is suspicious.'

Categories