简体   繁体   中英

Call specific items from lists stored in dictionaries in python

I'm trying to make a program in Python to store my school timetable. Partially for practice and partially for use. I have all my classes stored in a two dictionaries, one for week A and the other for week B. Here's an example of one of the dictionaries:

weeka = {
"Monday": ["Legal", "Religion", "English", "Maths", "Study"],
"Tuesday:": ["English", "History", "Legal", "Legal", "Study"],
"Wednesday": ["Study", "Maths", "English", "Religion", "History"],
"Thursday": ["Maths", "Study", "History", "Religion"],
"Friday": ["History", "Religion", "English", "Maths", "Legal"]}

def findClass(weekLetter, day, period):
    if weekLetter == "A" or weekLetter == "a":
        return {weeka[day][period]}
    elif weekLetter == "B" or weekLetter == "b":
        return {weekb[day][period]}
    else:
        return "Invalid input. Please try again."

When I run this, I get:

 Traceback (most recent call last):
  File "myTimetable.py", line 41, in <module>
    getClass()
  File "myTimetable.py", line 35, in getClass
    currentClass = findClass(weekLetter, day, period)
  File "myTimetable.py", line 19, in findClass
    return {weeka[day][period]}
KeyError: 4

Note that in the above error I have gotten all the argument mentioned in the function. How do I fix this?

So I believe this is what's wrong. The error Key Error means that you were passing in a key to a dictionary that wasn't an actual key in the dictionary. So for day instead of passing in for example 4 pass in “Thursday”

Edit: For example the dictionary a:

a = {“Monday” : [“Math”, “Writing”]
#if I wanted to get the value of Monday and get the first 
#subject the code would look like this
print(a[“Monday”][0])

So If I were to write this code, keeping the day part. I would do this

weeka = {
"Monday": ["Legal", "Religion", "English", "Maths", "Study"],
"Tuesday:": ["English", "History", "Legal", "Legal", "Study"],
"Wednesday": ["Study", "Maths", "English", "Religion", "History"],
"Thursday": ["Maths", "Study", "History", "Religion"],
"Friday": ["History", "Religion", "English", "Maths", "Legal"]}

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]

#Assuming that when you pass in the value day, day is not an exact index 
#value, meaning that for example if you wanted Monday, day would be 1

def findClass(weekLetter, day, period):
    if weekLetter == "A" or weekLetter == "a":
        return {weeka[days[day - 1]][period]}
    elif weekLetter == "B" or weekLetter == "b":
        return {weekb[days[day - 1]][period]}
    else:
        return "Invalid input. Please try again."

Your code seems to be working fine.Just pass the weekLetter and day as strings when you are calling function findClass.

weeka = {
"Monday": ["Legal", "Religion", "English", "Maths", "Study"],
"Tuesday:": ["English", "History", "Legal", "Legal", "Study"],
"Wednesday": ["Study", "Maths", "English", "Religion", "History"],
"Thursday": ["Maths", "Study", "History", "Religion"],
"Friday": ["History", "Religion", "English", "Maths", "Legal"]}

def findClass(weekLetter, day, period):
    if weekLetter == "A" or weekLetter == "a":
        return {weeka[day][period]}
    elif weekLetter == "B" or weekLetter == "b":
        return {weekb[day][period]}
    else:
        return "Invalid input. Please try again."

findClass('A','Wednesday',2)

This throws an error because of this weeka[day][period] here you are trying to access period (nested dictionary) which does not exist. to fix this I suggest you modify the weeka and weekb like this

 weeka = { 'Monday': { 'period_a': ["Legal", "Religion", "English", "Maths", "Study"], 'period_b': ["Legal", "Religion", "English", "Maths", "Study"] }, 'Tuesday': { 'period_a': ["Legal", "Religion", "English", "Maths", "Study"], 'period_b': ["Legal", "Religion", "English", "Maths", "Study"] }, 'Wednesday': { 'period_a': ["Legal", "Religion", "English", "Maths", "Study"], 'period_b': ["Legal", "Religion", "English", "Maths", "Study"] }, 'Thursday': { 'period_a': ["Legal", "Religion", "English", "Maths", "Study"], 'period_b': ["Legal", "Religion", "English", "Maths", "Study"] }, 'Friday': { 'period_a': ["Legal", "Religion", "English", "Maths", "Study"], 'period_b': ["Legal", "Religion", "English", "Maths", "Study"] }, } def findClass(weekLetter, day, period): if weekLetter.lower() == "a": return weeka[day][period] elif weekLetter.lower() == "b": return weekb[day][period] else: return "Invalid input. Please try again." period = findClass('A', 'Monday', 'period_a') print(period)

Note that I have changed if weekLetter == "A" or weekLetter == "a": to weekLetter.lower() == "a": this way you don't have to check same condition twice

A few challenges with your code.

#1: If the day of the week is not entered in the same format as its stored in the dictionary, you will get an error

#2: On Thursdays, you have only 4 periods. If you execute the current code, you will get an error. It will NOT return a valid message.

#3: You can combine both Week-A and Week-B into a single dictionary. The dictionary can have key a and key b . Each key can then have its own week of dictionary items. That way you can reference it with the same code.

#4: When you search for a period, you are actually giving the period #s 1 thru 5. Python stores it as 0 thru 4. So you will have to subtract 1 from period to get to the correct period.

Considering all these, here's a code that should address the above issues.

week_dict = {
    "a":{
        "Monday": ["Legal", "Religion", "English", "Maths", "Study"],
        "Tuesday": ["English", "History", "Legal", "Legal", "Study"],
        "Wednesday": ["Study", "Maths", "English", "Religion", "History"],
        "Thursday": ["Maths", "Study", "History", "Religion"],
        "Friday": ["History", "Religion", "English", "Maths", "Legal"]},
    "b":{
        "Monday": ["English", "History", "Legal", "Legal", "Study"],
        "Tuesday": ["Legal", "Religion", "English", "Maths", "Study"],
        "Wednesday": ["Maths", "Study", "History", "Religion"],
        "Thursday": ["Study", "Maths", "English", "Religion", "History"],
        "Friday": ["History", "Religion", "English", "Maths", "Legal"]}}

def findClass(weekLetter, day_of_week, period):
    print (weekLetter, day_of_week, period,end = ' : ')
    weekLetter = weekLetter.lower()
    day_of_week = day_of_week.capitalize()


    if weekLetter in ('a','b') and day_of_week in week_dict['a']:
        if period <= len(week_dict[weekLetter][day_of_week]):
            return week_dict[weekLetter][day_of_week][period-1]
        else:
            return "Invalid input. Please try again."
    else:
        return "Invalid input. Please try again."

print (findClass('A','monday',1))
print (findClass('a','tuesday',2))
print (findClass('a','wednesday',3))
print (findClass('a','thursday',5))
print (findClass('A','friday',4))

print (findClass('B','monday',1))
print (findClass('b','tuesday',2))
print (findClass('b','wednesday',3))
print (findClass('B','thursday',5))
print (findClass('b','friday',4))


print (findClass('a','saturday',2))
print (findClass('b','sunday',3))

The output of the following is:

A monday 1 : Legal
a tuesday 2 : History
a wednesday 3 : English
a thursday 5 : Invalid input. Please try again.
A friday 4 : Maths
B monday 1 : English
b tuesday 2 : Religion
b wednesday 3 : History
B thursday 5 : History
b friday 4 : Maths
a saturday 2 : Invalid input. Please try again.
b sunday 3 : Invalid input. Please try again.

Note: I have requested for Week A, Thursday, 5th period. There is none. It returns us an invalid entry.

Similarly, I am requesting for Week A and B on weekends. It also returns us an invalid entry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM