Python Dictionaries stuck - python

hope you are having a nice day, so I need to write a code that takes an input, which is going to be a key in an already existing dictionary, and prints the value as a str as described in the pic. I am stuck rn, I am a beginner and tried everything I see on the web related, appriciate any help, thank you.
[and these are the codes I tried][1]
def read_dataset(filename):
lines = open(filename).readlines()
lines_splitted = [line.strip().split(',') for line in lines]
return {lst[0]: lst[1:] for lst in lines_splitted}
movie_dict = read_dataset('dataset.txt')
# DO_NOT_EDIT_ANYTHING_ABOVE_THIS_LINE
hey = input('Enter a movie name: ')
actors = movie_dict[hey]
# DO_NOT_EDIT_ANYTHING_BELOW_THIS_LINE
print(','.join(sorted(actors)))
So this is my assignment

If you begin, try using pandas to make a dataframe of your base. It will be easier to use, and you should reuse it in a lot of cases.
Here an example of what you could do. If you don't understand a point, do not hesitate to ask me:
# import the package
import pandas as pd
# build the dataframe for the example
film = pd.DataFrame({'film':['Goldorak','Mickey Mouse'],'actors':[['Actarus','Alkor'],['Mickey, Minnie, Pluto, Goofy']]})
# the input
query = input('Enter the film')
# the 'search' engine
if len(film[film.film==query].actors)>0:
print(film[film.film==query].actors)
else:
print('not found in base')
EDIT with Dictionary :
FILM = {'Forest Gump':['Tom Hanks', 'Gary Sinise']}
query = None
query = input('Enter the film')
try:
print(FILM.get(query))
except:
pass

Related

Finding the line number of specific values in pandas dataframe - python

I am working on a school project and I am trying to simulate a library's catalogue system. I have .csv files that hold all the data I need but I am having a problem with checking if an inputted title, author, bar code, etc. is in the data set. I have searched around for quite a while trying different solutions but nothing is working.
The idea that I have right now is that if I can find at what line the inputted data, then I can use .loc[] to get the needed info.
Is this the right track? is there another, more efficient way to do this?
import pandas
mainData = pandas.read_csv("mainData.csv")
barcodes = mainData["Barcode"]
authors = mainData["Author"]
titles = mainData["Title/Subtitle"]
callNumbers = mainData["Call Number"]
k = "Han, Jenny,"
for i in authors:
if k == i:
print("Success")
k = authors.index[k]
print(authors[k])
else:
print("Fail" + k)
# Please Note: This code only checks for an author match and has all other fields left out as I thought this code was too inefficient to add the rest of the fields. The code also does not find the line on witch the matched are located, therefore .loc[] can not be used to print out all the data found.
This is the code I am using right now, It outputs the result along with an error Python IndexError: only integers, slices (\`:\`), ellipsis (\`\...\`), numpy.newaxis (\`None\`) and integer or boolean arrays are valid indices and is very slow. I would like the code to be able to output the books and their respective info. I have found the the .loc[] feature (mentioned above) outputs the info quite nicely. Here is the data I am using .
Edit: I have been able to reduce the time it takes for the program to run and made a functional "prototype"
authorFirst = authorFirst.lower()
authorFirst = authorFirst.title()
authorFirst += ","
authorSecond = input("Enter author's last name: ")
authorSecond = authorSecond.lower()
authorSecond = authorSecond.title()
authorSecond += ", "
authorInput = authorSecond + authorFirst
print(mainData[mainData["Author"].isin([authorInput])])
bookChoice = input("Please Enter the number to the left of the barcode to select a book: ")
print(mainData.loc[int(bookChoice)])
id provides the functionality that I am looking for but I feel that there has to be a better way of doing it. (Not asking the user to input the row number). Idk if this is possible tho.
I am new to python and this is my first time using pandas so i'm sorry if this is really shitty and hurts your brain.
Thank-you so much for your time!
Pandas does not really need to find the numeric index of something, to do indexing.
Since you have not provided any starting point or data, I'll just provide a few pointers here as there are mans ways to match and index things in pandas.
import pandas as pd
# build a library
library = pd.DataFrame({
"Author": ["H.G. Wells", "Hubert Selby Jr.", "Ken Kesey"],
"Title": [
"The War of the Worlds",
"Requiem for a Dream",
"One Flew Over the Cuckoo's Nest",
],
"Published": [1898, 1979, 1962],
})
# find on some characteristics
mask_wells = library.Author.str.contains("Wells")
mask_rfad = library["Title"] == "Requiem for a Dream"
mask_xixth = library["Published"] < 1900

How to insert a non-constant variable into a json url

Sorry for the incomprehensible title, hopefully, I can clarify. The first section of code works fine, but now I want to insert all of the "uuid's" into the requests and acquire something from each one in a for loop, perhaps.
import requests
import json
uuids = []
count = 0
catacombs = []
data = requests.get("https://api.hypixel.net/guild?key=42d64fe9-677c-433b-9460-f0177e0b9ded&id=5f1654598ea8c918612a6a43").json()
for guild in data["guild"]["members"]:
uuids.append(guild["uuid"])
Instead of having this...
data = requests.get("https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=0baac74f903143e49d24015d8bc3a733").json()
print(data)
I want to have the second parameter "profile" be taken from the previously acquired list like so.
data = requests.get("\"https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=" + str(uuids[count]) + "\"").json()
print(data)
I get a whole slew of errors and I don't know where to even start on fixing this. I will clarify if need be. Thanks in advance, and again sorry for any confusion.
There is no extra " at the ends of such urls, so change
data = requests.get("\"https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=" + str(uuids[count]) + "\"").json()
to
data = requests.get("https://api.hypixel.net/skyblock/profile?key=42d64fe9-677c-433b-9460-f0177e0b9ded&profile=" + str(uuids[count])).json()

How do I loop several inputs into a dictionary file Wirth Python?

My goal is to take two user inputs on a loop, save them in a dictionary, and when the user ends the loop, to have the save the dictionary.
# ------ Global Variables -------
user_cont = True
# ------- Functions -------
def get_Product():
while user_cont:
# get product code
get_ProductCode()
# get product number
get_ProductNum()
# save to dict
create_ProductDict()
# ask to continue
user_continue()
# save dict to file
def get_ProductCode(): works
def get_ProductNum(): works
def user_continue(): works but now is not getting prompted
What I'm currently trying to fix:
# save to dictionary
def create_ProductDict():
product_Dict = {}
productCode = get_ProductCode()
productNum = get_ProductNum()
print(product_Dict)
By my understanding on each loop, it should be receiving the returned productCode and productNum, and storing them? But now it won't ask the user to continue and end the loop so I can view the dictionary before I attempt to have the user save it.
In addition, I need to have the user choose a filename for the data.
As always, help is much appreciated!
There are two problems here. First issue is that your dictionary is being destroyed once the create_ProductDict() function ends, since the dictionary is created within the scope of the function.
One way to get around this would be to declare the dictionary in the global scope as a global variable. This way, the dictionary will persist as more items are added to it.
Next, your input variables currently aren't being used and the dictionary isn't being added to. The syntax for this is as follows:
productDict[productCode] = productNumber
So assuming that your input functions are equivalent to python's input() function, a solution that solves both of these issues would look something like this:
products = {}
def create_product_dict():
code = input("Enter Code: ")
num = input("Enter Number: ")
products[code] = num
create_product_dict()
create_product_dict()
print(products)
The output of this would be:
Enter Code: 123
Enter Number: 456
Enter Code: abc
Enter Number: 596
{'123': '456', 'abc': '596'}
Hope this is helpful :)
Try this:
def get_Product():
user_cont = True
while user_cont:
get_ProductCode()
get_ProductNum()
create_ProductDict()
user_cont = user_continue()
def user_continue():
ip = input('Enter Yes to Continue: ').lower()
return True if ip == 'yes' else False
Here is my finished main function after everything above pointed me in the direction I needed, but was not able to answer my questions entirely. My key finding was updating the dictionary before I asked to continue, and then adding the saving of the dictionary at the end. (The additional functions not included here as did not pertain to question/solution. Thank you!
user_cont = True
while user_cont:
# get product code
productCode = get_ProductCode()
# get product number
productNum = get_ProductNum()
# print(productCode, productNum)
# save to dict
products[productCode] = productNum
# debug to ensure dictionary was saving multi lines
# print(products)
# ask to continue
user_cont = user_continue()
for productCode, productNum in products.items():
formproducts = (productCode + ", " + productNum)
# print test
# print(formproducts)
# save dict to file
FILENAME = input(str("Please enter a file name: "))
file = open(FILENAME, "w")
file.write( str(products) )
file.close()
print("File saved.")

Python, returning the integer from a tuple from an input

I am trying to make the input command streamlined, I don't know if I can explain this but here it goes.
out = input()
planOne = int(out)
planet = listplanets[planOne]
print(planet)
So listplanets is a tuple, if I input a number such as 0, it will return Mercury, how do I make it so I can input mercury and it will return Mercury. I want to keep the tuple format and I will also need the integer value of the tuple item in say var1. Would be greatly appreciated if someone can help me out. PS I know, I am a massive noob XD.
Edit: This is how my tuple is made
listplanets = ("Mercury"), (0.378), ("Venus"), (0.907), ("Mars"), (0.377), ("Io"), (0.1835), ("Europa"), (0.1335), ("Ganymede"), (0.1448), ("Callisto"), (0.1264)
Edit:
I am now using a dictionary, as suggested by you kind people.
listplanets = {
"Mercury": "Mercury",
"Mercury2": 0.378,
"Venus": "Venus",
"Venus2": 0.907,
"Mars": "Mars",
"Mars2": 0.377,
"Io": "Io",
"Io2": 0.1835,
"Europa": "Europa",
"Europa2": 0.1335,
"Ganymede": "Ganymede",
"Ganymede2": 0.1448,
"Callisto": "Callisto",
"Callisto2": 0.1264}
My reason for structuring it this way was for printing purposes, I am overcomplicating this!
I am not sure if it is against the rules to ask another question but it does relate to this post.
I am now trying to have it so when you type in mercury it will output On the planet of Mercury, this code below is not working for me, more help would be massively appreciated!
out = input().capitalize()
if out == listplanets:
print("On the planet of", listplanets[out])
else:
print("That was an incorrect format! Try again.")
planets()
For anyone that is curious, here is my code (Reason why it is not text is because this is my assignment, the anti plagerise tool would say I am copying my own code! XD):
---------------------------------------
The previous part was not shown clearly and that is why there is an image there
You can't use the slice operator directly listplanets[out] on a dictionary.
And you don't have to repeat the same thing over and over"mercury": "Mercury".
Use this format for your dictionary,
listplanets = {"Mercury": 0.378, "Venus": 0.907, "Mars": 0.377, "Io": 0.1835, "Europa": 0.1335, "Ganymede": 0.1448, "Call
and try this
out = input()
if out.isdigit(): #check if the input is digit
print(list(listplanets.keys())[int(out)]) #gets all key values to a list and so slicing can done
else:
print(listplanets[out.capitalize()]) #capitalize first letter
If you need to keep it tuple format you have to loop through your data like this:
# Data is given like this. First name and then value related to it.
listplanets = ("Mercury"), (0.378), ("Venus"), (0.907), ("Mars"), (0.377), ("Io"), (0.1835), ("Europa"), (0.1335), ("Ganymede"), (0.1448), ("Callisto"), (0.1264)
out = input("Planet: ")
for i in range(len(listplanets)):
if isinstance(listplanets[i], float):
# Skip values
continue
if out.lower() == listplanets[i].lower():
print ("{}: {}".format(listplanets[i], listplanets[i+1]))
But using dictionary is much better, as mentioned in comments.
How about this code?
# listplanets = ('Mercury', 'Earth')
In [19]: new_listplanets = [(index, {planet.lower(): planet}) for index, planet in enumerate(listplanets)]
# [(0, {'mercury': 'Mercury'}), (1, {'earth': 'Earth'})]
In [20]: new_listplanets[0][0]
Out[20]: 0
In [21]: new_listplanets[0][1]['mercury']
Out[21]: 'Mercury'

How can I get user input for an array?

I want to create a list from a user's input and then return a random value from that list.
This is what I have so far for the code but I can't figure out how to get input for the array.
import random
movie_array = ["movieA", "movieB", "movieC"]
print(random.choice(movie_array))
I know about the input function but I'm not sure how to use it to create an array/list. I tried the following but it didn't work
movie_array = input()
but when I run the random.choice on that it only selects an individual character.
You can do it like this:
>>> import random
>>> movie_array = [input("Input a movie: ") for i in range(3)]
Input a movie: movieA
Input a movie: movieB
Input a movie: movieC
>>> print(random.choice(movie_array))
movieC
Use a loop.
In the body of the loop prompt the user to enter a movie title, or 'q' to quit. Append each entry to your movie list. When finished select a random movie from the movie list:
import random
movies = []
while True:
entry = input('Enter a movie title (q to quit): ')
if entry.lower() == 'q':
break
movies.append(entry)
if movies:
print(random.choice(movies))
Hopefully your users do not want to enter the movie entitled "Q" (1982). It might be better to use an empty entry as the sentinel, like this:
entry = input('Enter a movie title (<Enter> to quit): ')
if entry == '':
break
You can read movies in a single line separated by commas and then split it into array.
movie_array=raw_input("Enter Movies").split(',')
If it is python 3.x
movie_array=input("Enter Movies").split(',')
Just want to clarify why your solution attempt didnt work IE this:
movie_array = input()
It's because the input returns a string I.E a list of substrings so
you can seemovie_array = 'test' asmovie_array = ['t','e','s','t']
print(movie_array[1])
>>>'e'
in order to solve your problem I would recommend #mhawke answer (using a while loop)
By using a while loop you can retrieve multiple inputs and store each of them in a list. Be aware though that a while loop has to be able to "END" or it can cause problems. Therefore you have to have a break somewhere in the while loop.
Otherwise the program would be run indefinetly until you either forced it to shutdown or until it crashes.
Further information about this can be read here:
Tutorialspoint (Strings)
Tutorialspoint (Whileloop)
also checkout the official wiki for strings and control flow.
You can give it like this.
movie_array = [b for b in input().split()]
And then you can get input from user like this,
movieA movieB movieC

Categories