How to search & output a data in python? - python

First of all, I'm a newbie to Python. I'm just practicing.
I have made users to input a certain data into the memory by using append.
store = []
def inputData():
name = input("Name: ")
amount = input("Amount: ")
date = input("Data: ")
store.append({'name':name, 'amount':amount, 'date':date})
I want to let users be able to search the data stored in the memory.
Any hints would be really appreciated.
======================================
Here is my output code
def outputData():
print("="*30)
print("Name / Amount / Date")
print("="*30)
for d in store:
print("%(name)s %(amount)s %(date)s"%d)

def outputData(data):
print("="*30)
print("Name / Amount / Date")
print("="*30)
for person in data:
print("{name} {amount} {date}".format(**person))
Where 'data' is the dictionary where you store the values.

Related

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

How to let the multiply keys all exist in dictionary? (python)

I have a problem.
I wanna add the same record but the old one will be replaced by a new one! I want both of them exist so I can see what I've done.
How do I solve the problem? Please help me!
Thank you!
my code:
initial_money = int(input('How much money do you have? '))
mr={}
add_mr={}
def records():
return
def add(records):
records = input('Add an expense or income record with description and amount:\n').split()
global mr
global rec
rec = records[0]
global amt
amt = records[1]
for r, a in mr.items():
i = 0
while (r, i) in add_mr:
i += 1
add_mr[(r, i)] = a
global initial_money
mr[rec] = int(amt)
initial_money += mr[rec]
def view(initial_money, records):
print("Here's your expense and income records:")
print("Description Amount")
print("------------------- ------")
for r,a in mr.items():
print('{name:<20s} {number:<6s}'.format(name = r,number = str(a)))
print('Now you have {} dollars.'.format(initial_money))
while True:
command = input('\nWhat do you want to do (add / view / delete / exit)? ')
if command == 'add':
records = add(records)
elif command == 'view':
view(initial_money, records)
The output:
How much money do you have? 1000
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? add
Add an expense or income record with description and amount:
ewq 87
What do you want to do (add / view / delete / exit)? view
Here's your expense and income records:
Description Amount
------------------- ------
tree 87
Now you have 1174 dollars.
Output I want:
------------------- ------
tree 87
tree 87
Instead of using a dictonary such that Mr = {"ewq": 87} you could instead use a list of all of them such that Mr = [("ewq", 87), ("ewq", 87)]
This would make it so that if you have a duplicate it won't overwrite. As dictionaries can only have one per key
Edit: You would do this by replacing the first part that says mr = {} with mr = [] and then whenever you call addmr you can instead just use mr.append(value) which will add the value to the list
You actually can do this with a dict. In stead of one item per key use one list per key.
if rec not in mr:
mr[rec] = []
mr[rec].append(amt)
Such that mr = {"ewq": [87, 87]}

Spyder Unresponsive

so I am using Spyder IDE for python. it stopped executing my codes, I have tried to run only a few lines and all together but still no response.
Anyone familiar with these sort of issues?
#Assinging Variables
ProductName = "iPhone"
ProductPrice = 450
Tax = 0.5 #Tax is a constant that cannot be changed
print(ProductTax)
#Dealing with Inputs
name = input("Your Name")
print(name)
print("Hello", name)
city = input("Where do you live?")
print(name, "lives in", city)
#CASTING - converting one data type to another as examples below.
##Note that all the answers required below will be in form of strings
ProductName = input("what is the product Name?")
ProductPrice = float(input("how much is it cost?")) #the string is converted to float
ProductQuantity = int(input("How many?")) #the string is converted to an integer
TotalPrice = ProductQuantity*ProductPrice
print("Total Price: ", TotalPrice)
##SELECTION
## selection is used to choose between 2 or more otions in programming
## if statements is a type of 'selection'
#weather = input("is it raining")
#if weather == "raining":
#print ("Grab an Umbrella")
#else:print("Wear a coat")
it works for me when create a new Console. Hope that works for you.
enter image description here

How to delete the pickled object from a file?

I've got a problem while I was doing a program. My program is to create a class student and there are some variables under that and my task is to add the students in a serializable file and delete the students whenever user wants to. I have written the code for adding the students but I am stuck while delete the object. I am very thankful if anyone could help me how to delete a pickled object from a file?
my code is:
import pickle
n = int(input("Enter number of students you want to enter:"))
for i in range(0,n):
name = input("Enter student name: ")
roll = input("Enter roll number: ")
sex = input("Enter sex: ")
sub = input("Enter subject: ")
tot = input("Enter total: ")
s = Student(name,roll,sex,sub,tot)
infile = open("pb.txt","ab")
pickle.dump(s,infile)
infile.close()
and my student class is:
class Student:
def __init__(self,name,roll,sex,sub,tot):
self.name = name
self.roll = roll
self.sex = sex
self.sub = sub
self.tot = tot
One way could be to pickle a list of students. Then when you want to delete, you can read from file, delete as normal e.g. students.remove(), and then pickle again.
Pickle files aren't editable, and they were never meant to be. If you need to track individual pickled items, look at the shelve module - this lets you treat an external collection of (pickled) objects like a dictionary with string keys.

Python List in List ("Stuck")

def lists(): #Where list is stored
List = ["Movie_Name",[""],"Movie_Stars",[""],"Movie_Budget",[""]]
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
Budget = input ("Budget ...")
List.append["Movie_Name"](film)
List.append["Movie_Stars"](stars)
List.append["Movie_Budget"](Budget)
lists()
How do i add the film you enter to the list under the subsetting Movie_Name etc?
A better answer than one which answers your question directly would be: You don't. You definitely need a dictionary for this situation (unless your program develops to a point where you'd prefer creating a custom object)
As a simple demonstration:
def getMovies():
movieinfo = {"Movie_Name": [], "Movie_Stars": [], "Movie_Budget": []}
print ("Your Movies")
amount_in_list = int(input("How many Movies? "))
x = 1
while x <= amount_in_list:
film = input ("Name of film ... ")
stars = input ("Main stars ...")
budget = input ("Budget ...")
movieinfo["Movie_Name"].append(film)
movieinfo["Movie_Stars"].append(stars)
movieinfo["Movie_Budget"].append(budget)
x+=1
return movieInfo
Notice that with a dict you simply use the key string to get the corresponding list (initialized at the start of the function) and append the data as desired.
Edited to provide further information for OP's updated request.
If you want to find a movie's info based on just the movie's name given by the user, you could try something like this:
film = 'The Matrix' # Assuming this is the user's input.
Try:
# The index method will throw an exception if
# the movie cannot be found. If that happens,
# the 'except' clause will execute and print
# the relevant statement.
mIdx = movieinfo['Movie_Name'].index(film)
print '{0} stars {1} and had a reported budget of {2}'.format(
film, movieInfo['Movie_Stars'][mIdx], movieInfo['Movie_Budget'][mIdx])
except ValueError:
print '{0} is not in the movie archives. Try another?'.format(film)
Output:
'The Matrix stars Keanu Reeves and had a reported budget of $80 million'
Or:
'The Matrix is not in the movie archives. Try another?'
I would store the movie information in an object. This way your code will be easier to extend, make changes and reuse. you could easily add methods to your movie class to do custom stuff or add more properties without having to change your code to much.
class Movie:
def __init__(self, name='', actors=[], rating=0 budget=0):
self.name=name
self.actors=actors
self.budget=budget
self.rating=rating
def setName(self, newname):
self.name=newname
def setActors(self, newstars):
self.actors=newstars
def setBudget(self, newbudget):
self.budget=newbudget
def setRating(self, newrating):
self.rating=newrating
# example
mymovies=[]
movie1= Movie('Interstellar',['actor1','actor2','actor3'], 5, 100000)
movie2=Movie()
movie2.setName('other movie')
movie2.setActors(['actor1','actor2','actor3'])
movie2.setBudget(10000)
mymovies.append(movie1)
mymovies.append(movie2)
# or append to your list in a loop

Categories