Search within a dictionary with a lot of values in python - python

In the following code I'm showing a function that lets you add students to a dictionary (book) with rut being the key, the issue I have is that I'm trying to make a function that can search by department and then print all students of that are part of that department, basically I'm asking how do you search a dictionary with 1 key that is associated to a lot of values and you want to search for a particular value and then print all keys that have it along with their info?
book = {}
def add(rut, name, age, department):
student = {}
student['rut'] = rut
student['name'] = name
student['age'] = age
student['department'] = department
book[rut] = student
def printall():
for rut in book:
student = book[rut]
print(student['rut'], student['name'], student['age'], student['department'])
def main():
count = 0
x = 0
y = int(input("How many students will you add?: "))
while count < y:
print('Input data of the student: ', count+1)
rut = input("rut: ")
name = input("name: ")
age = int(input("age: "))
print("Department 1: RH, 2: Logistic, 3: Cleaners, 4: TI ")
department = ''
while x == 0:
num_dept = int(input("department number: "))
if num_dept == 1:
department = "RH"
x = 1
elif num_dept == 2:
department = "Logistic"
x = 1
elif num_dept == 3:
department = "Mathematics"
x = 1
elif num_dept == 4:
department = "TI"
x = 1
else:
print('Error')
x = 0
add(rut, name, age, department)
count = count + 1
printall()
main()

You can use a list comprehension.
students = [student for student in book.values()
if student["department"] == desired_department]
This will give you a list, which you can then print out if you so choose.

Related

finding the highest hour in a list

class volunteerList:
def __init__ (self, groupName):
self.__vList = []
self.__groupName = groupName
def setGroupName (self, newGroupName):
self.__groupName = newGroupName
def getGroupName (self):
return self.__groupName
def getvList (self):
return self.__vList
def addVolunteer (self, volunteer):
self.getvList().append(volunteer)
def highestHour (self):
details = ""
highestHourList = []
highest = self.__vList[0].getHourContribution()
for volunteer in self.__vList:
hour = volunteer.getHourContribution()
if hour == highest:
highestHourList.append(hour)
elif hour > highest:
highestHourList = [hour]
highest = hour
#highestHourList.append(hour)
if volunteer.getType().lower() == "f":
details = details + "{} - {} years old - flood volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "p":
details = details + "{} - {} years old - pandemic volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "e":
details = details + "{} - {} years old - earthquake volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
elif volunteer.getType().lower() == "t":
details = details + "{} - {} years old - tsunami volunteer".format(volunteer.getName(), volunteer.getAge()) + "\n"
return details
def main ():
groupName = input("Enter your group name: ")
newGroup = volunteerList(groupName)
print ("\n")
choice = menu()
while choice != "0":
if choice == "1":
name = input("Name of volunteer? ")
age = int(input("Age? "))
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
while volunteerType not in "fpet":
print ("Invalid type! Please enter again!")
volunteerType = input("Type of volunteer ('F/P/E/T'): ")
volunteerType = volunteerType.lower()
hourCont = int(input("Contribution hour? "))
while hourCont <= 0:
print ("Invalid value! Please enter again!")
hourCont = int(input("Contribution hour? "))
newGroup.addVolunteer(volunteer(name, age, volunteerType, hourCont))
print ("... Volunteer has been added successfully.")
print ("\n")
choice = menu()
elif choice == "6":
print ("Volunteer with highest contribution hour:")
print (newGroup.highestHour())
print ("\n)
I'm not sure the code on highestHour() correct or wrong. I was planning to find the highest hour of the volunteer(s). If there are more than 1 highest hour of volunteer (same hour), display everything. My output was only one highest hour of volunteer or display 2 same line of statement instead of the example before.
Wondering how to display all volunteer that are highest hour?
The display sample will be:
a - 36 years old - pandemic volunteer
b - 25 years old - flood volunteer
Here you go:
class volunteer:
def __init__ (self, name, age, type, hourContribution):
self.__name = name
self.__age = age
self.__type = type
self.__hourContribution = hourContribution
def getHourContribution (self):
return self.__hourContribution
class volunteerList:
def __init__ (self, groupName):
self.vList = []
self.__groupName = groupName
def highestHour (self):
highHourList = []
hourList = []
for volunteer in self.vList:
hourList.append(volunteer.getHourContribution())
highest = max(hourList)
for hour in hourList:
if hour == highest:
highHourList.append(hour)
print(highHourList)
new = volunteerList("one")
vol1 = volunteer("", 1, "", 5)
vol2 = volunteer("", 1, "", 10)
vol3 = volunteer("", 1, "", 10)
vol4 = volunteer("", 1, "", 10)
vol5 = volunteer("", 1, "", 1)
new.vList = [vol1, vol2, vol3, vol4, vol5]
new.highestHour()
Alternative highestHour function
def highestHour (self):
highHourList = []
largest = self.vList[0].getHourContribution()
for volunteer in self.vList:
hour = volunteer.getHourContribution()
if hour == largest:
highHourList.append(hour)
elif hour > largest:
highHourList = [hour]
largest = hour
print(highHourList)
Needs some cleaning up, but you get the idea.

Python file not reading data but putting repetetive values in list

Hi I am reading data from file in the class Patients and passing the content to appointment class method.
when the content is split such that content[0] has ['130', 'Ali', 'Male', '22', 'Cough'] so I am putting these values and setting the Patient class properties. This is done in for loop so all objects from file read are added to list of Patient class. But in doing so it is repetitively adding only one row of data.
Below is the code:
//Text file Data:
ID PatientName Gender Age Disease
130 Ali Male 22 Cough
132 Annile Female 23 Corona
133 sam Male 24 Fever
I want list of patients to store 130-132-133 but instead it stores only 133 at all three positions of list. Dont know if object creation or passing for Patient class is an issue
//Patient.py
class Patients:
def __init__(self):
self.patient_id = ""
self.patient_name = ""
self.patient_age = ""
self.patient_gender = ""
self.patient_disease = ""
def read_patient_file(self):
with open('PatientRecord.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
del content[0] // first row is of column names so removing it
return content
//Appointment.py
def patientProgram(list_patient):
Flag = True
pat1 = Patients()
while Flag:
print("\nPress 1. To Create Patient Record ")
print("Press 2. To View Patient Records ")
print("Press 6. To Read Patient Record From File ")
x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
if x == 1:
list_patient.append(AddPatient())
elif x == 2:
print("**********")
print("Total Records in Memory for Patients:" + str(len(list_patient)))
for pat in list_patient:
print(f'patient_id = {pat.patient_id} for object {pat}')
elif x == 6: // this condition gives issue
content = []
content = pat1.read_patient_file() // content gets 3 rows of data from text file
j = 0
for i in content:
pat_id, name, gender, age, disease = str(content[j]).split()
print("FirstID: " + str(j)+ str(pat_id))
pat1.set_patient_record(pat_id, name, gender, age, disease)
list_patient.append(pat1)
j=j+1
print("Total Records for Patients in memory : " + str(len(list_patient)))
from Patients import Patients
if __name__ == "__main__":
list_patient = []
Flag = True
while Flag:
print("\nPress 1. For Patient Options ")
print("Press 2. For Doctor Options ")
print("Press 3. To Exit Program ")
x = int(input("Please Select From Menu:"))
if x == 1:
patientProgram(list_patient)
elif x==3:
break
You're only creating one Patients object. For each record in the file, you modify the pat1 object and append it to the list_patient list. So all the list elements are the same object.
You need to create a new object for each record in the file, not one object at the beginning.
Also, the read_patient_file() function should be a class method, since it doesn't use self for anything.
class Patients:
def __init__(self):
self.patient_id = ""
self.patient_name = ""
self.patient_age = ""
self.patient_gender = ""
self.patient_disease = ""
#classmethod
def read_patient_file(cls):
with open('PatientRecord.txt') as f:
content = f.readlines()
content = [x.strip() for x in content]
del content[0] // first row is of column names so removing it
return content
def patientProgram(list_patient):
Flag = True
while Flag:
print("\nPress 1. To Create Patient Record ")
print("Press 2. To View Patient Records ")
print("Press 6. To Read Patient Record From File ")
x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
if x == 1:
list_patient.append(AddPatient())
elif x == 2:
print("**********")
print("Total Records in Memory for Patients:" + str(len(list_patient)))
for pat in list_patient:
print(f'patient_id = {pat.patient_id} for object {pat}')
elif x == 6: // this condition gives issue
content = []
content = Patients.read_patient_file() // content gets 3 rows of data from text file
j = 0
for i in content:
pat1 = Patients()
pat_id, name, gender, age, disease = str(content[j]).split()
print("FirstID: " + str(j)+ str(pat_id))
pat1.set_patient_record(pat_id, name, gender, age, disease)
list_patient.append(pat1)
j=j+1
print("Total Records for Patients in memory : " + str(len(list_patient)))

I'm giving 'int' to append but again throwing ERROR

def find_gpa(sem=1):
sub = int(input("Enter the no of subjects: "))
credits = []
grade = []
temp = []
for i in range(0,sub):
a=i+1
x = int(input("Enter the credits for subject {}".format(a)))
credits.append(x)
grade = input("Enter the Grade for subject {}".format(a))
y = gpa_convert(grade)
print(type(y))
grade.append(y)
temp.append(x*y)
gpa = sum(temp)/sum(credits)
tup = (gpa,sum(credits))
print ("The Gpa of semester {} is: {}".format(sem,gpa))
return tup
def gpa_convert(z):
if z.lower() == 'o':
return 10
elif z.lower() == 'a+':
return 9
elif z.lower() == 'a':
return 8
elif z.lower() == 'b+':
return 7
elif z.lower() == 'b':
return 6
else :
return 0
AttributeError:
'str' object has no attribute 'append'
I'm trying to append an integer in grade but its showing string
can you help me in rectifying the error?
You start with
grade = []
but in your loop you have :
grade = input("Enter the Grade for subject {}".format(a))
your list doesn't exist anymore, grade is now an int
int don't have append method, so this doesn't work :
grade.append(y)
Solution :
replace grade = [] by grades = [] and then use plural where a list is expected
def find_gpa(sem=1):
sub = int(input("Enter the no of subjects: "))
credits = []
grades = []
temp = []
for i in range(0,sub):
a=i+1
x = int(input("Enter the credits for subject {}".format(a)))
credits.append(x)
grade = input("Enter the Grade for subject {}".format(a))
y = gpa_convert(grade)
print(type(y))
grades.append(y)
temp.append(x*y)
gpa = sum(temp)/sum(credits)
tup = (gpa,sum(credits))
print ("The Gpa of semester {} is: {}".format(sem,gpa))
return tup
Please note however that you declare a list in the scope of the function, but never use it or return it ! This code can be simplified a lot

Return multiple values in a function

I am doing a University project to create a plan ordering ticket program, so far these are what I have done:
First, this is the function finding the seat type:
def choosingFare():
print("Please choose the type of fare. Fees are displayed below and are in addtion to the basic fare.")
print("Please note choosing Frugal fare means you will not be offered a seat choice, it will be assigned to the ticketholder at travel time.")
listofType = [""] * (3)
listofType[0] = "Business: +$275"
listofType[1] = "Economy: +$25"
listofType[2] = "Frugal: $0"
print("(0)Business +$275")
print("(1)Economy +$25")
print("(2)Frugal: $0")
type = int(input())
while type > 2:
print("Invalid choice, please try again")
type = int(input())
print("Your choosing type of fare is: " + listofType[type])
if type == 0:
price1 = 275
else:
if type == 1:
price1 = 25
else:
price1 = 0
return price1, listofType[type]
And this is a function finding the destination:
def destination():
print("Please choose a destination and trip length")
print("(money currency is in: Australian Dollars: AUD)")
print("Is this a Return trip(R) or One Way trip(O)?")
direction = input()
while direction != "R" and direction != "O":
print("Invalid, please choose again!")
direction = input()
print("Is this a Return trip(R) or One Way trip(O)?")
if direction == "O":
print("(0)Cairns oneway: $250")
print("(2)Sydney One Way: $420")
print("(4)Perth One Way: $510")
else:
print("(1)Cairns Return: $400")
print("(3)Sydney Return: $575")
print("(5)Perth Return: $700")
typeofTrip = [""] * (6)
typeofTrip[0] = "Cairns One Way: $250"
typeofTrip[1] = "Cairns Return: $400"
typeofTrip[2] = "Sydney One Way: $420"
typeofTrip[3] = "Sydney Return: $575"
typeofTrip[4] = "Perth One Way: $510"
typeofTrip[5] = "Perth Return: $700"
trip = int(input())
while trip > 5:
print("Invalid, please choose again")
trip = int(input())
if trip == 0:
price = 250
else:
if trip == 1:
price = 400
else:
if trip == 2:
price = 420
else:
if trip == 3:
price = 574
else:
if trip == 4:
price = 510
else:
price = 700
print("Your choice of destination and trip length is: " + typeofTrip[trip])
return price, typeofTrip[trip]
And this is the function calculating the total price:
def sumprice():
price = destination()
price1 = choosingFare()
price2 = choosingseat()
sumprice = price1 + price2 + price
print("How old is the person travelling?(Travellers under 16 years old will receive a 50% discount for the child fare.)")
age = float(input())
if age < 16 and age > 0:
sumprice = sumprice / 2
else:
sumprice = sumprice
return sumprice
The error I have:
line 163, in <module> main()
line 145, in main sumprice = sumprice()
line 124, in sumprice
sumprice = price1 + price2 + price
TypeError: can only concatenate tuple (not "int") to tuple
Can someone help me? I am really stuck.
I can't return all the
These functions return 2 values each: destination(), choosingFare(), choosingseat().
Returning multiple values at once returns a tuple of those values:
For example:
return price, typeofTrip[trip] # returns (price, typeofTrip[trip])
So while calculating the sum of all prices, you need to access price, price1, price2 from the tuples:
sumprice = price1[0] + price2[0] + price3[0]
Alternatively: You can edit the code to return list/ dictionary or some other data structure as per your convenience.
First let me explain what happends when you write. return price, typeofTrip[trip].
The above line will return a tuple of two values.
Now for sumprice I think what you want is sum of all prices. So you just want to sum first element of returned values.
This should work for your case.
sumprice = price1[0] + price2[0] + price3[0]

How to return the nth value of a Dict?

I have this dict for example and i wish to return the nth value of it
d = {'Hello':4, 'World':17, 'Hi':2, 'Again':46}
Note: I know that dicts are unordered, and i don't care i just want to return all the keys one after the other.
In my program I just want to make calculations with the values, and the keys will be a user input so we don't know the keys.
How can i return the nth value in this dict like this?
Hereis the full code of y progam, error is located in 2nd def function, on line 23
#Subroutines
def dumptodaydate():
import pickle
with open('LastOpenDate.txt', 'wb') as DOT:
import time
ODate = time.strftime('%d')
OMonth = time.strftime('%m')
OYear = time.strftime('%Y')
List = {'Day':ODay, 'Month':OMonth, 'Year':OYear}
pickle.dump(List, DOT)
def caltimelefttask():
import pickle
with open('LastOpenDate.txt', 'rb') as LOD:
List = pickle.load(LOD)
from datetime import date
Today = date.today()
ODay = List['Day']
OMonth = List['Month']
OYear = List['Year']
DifDay = (Today(eval(OYear),eval(OMonth), eval(ODay)).days
for key in Lesson:
OTimetask = Lesson[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Lesson[key]['Rating'] = Rating
for key in Exercises.keys():
OTimetask = Exercises[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Exercises[key]['Rating'] = Rating
for key in Assignment.keys():
OTimetask = Assignment[key]['TimeLeftTask']
TimeLeft = OTimetask - DifDay
Rating = Rating + (TimeLeft * 2)
if Timeleft == 0 and OTimetask > 3:
Rating = Rating + 100
elif OTimetask > 0 and TimeLeft == 0:
Rating = Rating + 50
elif OTimetask > 4 and imeLeft == 0 and OTimetask != 0:
Rating = Rating + 50
Assignment[key]['Rating'] = Rating
def loadtxt():
import pickle
with open('LessonOut.txt', 'rb') as Li:
Lesson = pickle.load(Li)
with open('ExercisesOut.txt', 'rb') as Ei:
Exercises = pickle.load(Ei)
with open('AssignmentOut.txt', 'rb') as Ai:
Assignment = pickle.load(Ai)
def ADD():
print('Name of task? (Keep it short for convenience Example: Math1)\n(Must be diferent from any other non deleted tasks)')
Name = input('>>>')
print('Description of task? (this can be as long as you want)')
Desc = input('>>>')
print('Rate the time it takes you to do the task on a scale from 1 to 20')
Time = input('>>>')
print('Rate the importance of the task on a scale from 1 to 20')
Imp = input('>>>')
print('Rate how much you want to do it on a scale from 1 to 5 \n(1= want to do it, 5= don\'t want to')
Want = input('>>>')
print('enter deadline (day)')
TimeDay = input('>>>')
print('enter deadline (month)')
TimeMonth = input('>>>')
print('enter deadline(year)')
TimeYear = input('>>>')
print('what type of homework is it? (Lesson/Exercises/Assignment)')
TaskType = input('>>>')
from datetime import date
Today = date.today()
TaskForDate = date(eval(TimeYear), eval(TimeMonth), eval(TimeDay))
TimeLeftTemp = abs((TaskForDate - Today).days)
print ('You have', TimeLeftTemp, 'days to finish this task.')
Rating = eval(Time) + eval(Imp) + eval(Want) - (TimeLeftTemp * 2)
if TimeLeftTemp < 4:
Rating = Rating + 50
if TimeLeftTemp <= 0:
Rating = Rating + 50
if TaskType == 'Lesson':
Lesson[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Exercises':
Exercises[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
if TaskType == 'Assignment':
Assignment[Name] = {'Rating':Rating, 'Desc':Desc, 'TimeLeftTask':TimeLeftTemp}
def DEL():
print ('What type of task is it? \nLesson, Exercises or Assignment)')
WhatDict = input('>>>')
if WhatDict == Lesson:
print(Lesson.keys())
if WhatDict == Exercises:
print(Exercises.keys())
if WhatDict == Assignment:
print(Assignment.keys())
print ('What task do you want do delete?')
WhatDel = input('>>>')
if WhatDict == 'Lesson':
try:
del Lesson[WhatDel]
except:
pass
elif WhatDict == 'Exercises':
try:
del Exercises[WhatDel]
except:
pass
elif WhatDict == 'Assignment':
try:
del Assignment[WhatDel]
except:
pass
pass
else:
print('Sorry, the type of task is not recognised, please try again.')
def sort_by_subdict(dictionary, subdict_key):
return sorted(dictionary.items(), key=lambda k_v: k_v[1][subdict_key])
def SHOW():
ShowWhat = input('What type of task do you want to do?\nLesson/Exercises/Assignment)\n>>>')
if ShowWhat == 'Lesson' or 'lesson':
print (sort_by_subdict(Lesson, 'Rating'))
elif ShowWhat == 'Exercises' or 'exercises':
print (sort_by_subdict(Exercises, 'Rating'))
elif ShowWhat == 'Assignment' or 'assignment':
print (sort_by_subdict(Assignment, 'Rating'))
else:
print('Type of task not recognosed, please try again')
def dumptxt():
import pickle
with open('LessonOut.txt', 'wb') as Lo:
pickle.dump(Lesson, Lo)
with open('ExercisesOut.txt', 'wb') as Eo:
pickle.dump(Exercises, Eo)
with open('AssignmentOut.txt', 'wb') as Ao:
pickle.dump(Assignment, Ao)
loadtxt()
while True:
print ('WARNING NEVER EXIT PROGRAM WITHOUT USING THE quit COMMAND,\nOR ALL ACTIONS DONE WILL BE LOST')
print ('Commands:')
print ('add (to add a task)')
print ('del (to delete a task)')
print ('quit (to exit program)')
print ('show (to see your tasks)')
Input = input('>>>')
if Input == 'add':
ADD()
elif Input == 'del':
DEL()
elif Input == 'show':
SHOW()
elif Input == 'quit':
print ('are you sure you want to quit? y/n')
Input = input('>>>')
if Input == 'y':
dumptxt()
quit()
elif Input == 'n':
print ('Not exiting')
else:
print ('Error, command not recognised')
This gives me a syntax error:
for key in Lesson:
#syntax error ^
# here
You can just enumerate over all the keys in the dict directly by using for key in d:
for key in d:
if d[key] < 20:
d[key] -= 4
else:
d[key] += 4

Categories