Home > Software design >  Getting a name of a key from a dictionary
Getting a name of a key from a dictionary

Time:05-11

I'm currently learning python and I'm struggling in a problem which I need to get a name as input from a user and get the first letter of the name and depending on the letter, tell him what day of the week he needs to go (context doesn't matter), so: Monday: A - C; Tuesday: D - G; Wednesday: H - L; Thursday: M; Friday: N - Q; Saturday: R - S; Sunday: T - Z.

tuple_letter = (['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j', 'k', 'l'], ['m'], ['n', 'o', 'p', 'q'], ['r', 's', 't'], ['u', 'v', 'w', 'x', 'y', 'z'])
tuple_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 

name = input("Name: \n")
for letters in tuple_letter:
    if letters.count(name[0]) >= 1:
         print(name   ", you should go to the hospital on "   tuple_week[letters])

I thought that just like in c# for example, "letters" inside the for, it'd actually act like the i , that it counts as a number but in fact, python itself knows that when we say "for letters in tuple_letter" I'm actually refering to the lists inside the list "tuple_letter", so it does not work since I was basing my logic on the fact that I'd use it to refer to the element of each list, because i put each element of each list in the same order (Monday and 'a','b','c' == 1, ....)

To conclude and connect with the title, I had an idea where I'd create a dictionary where each key would be the respective day of the week for a list of letters, just like I tried. So, how can I do this? Is it possible? Better ways?

CodePudding user response:

You can, it might make a bit more logical sense. Working with dictionaries can be easy in Python since they follow the standards of JSON. Obligatory reading here: https://www.w3schools.com/python/python_dictionaries.asp

Your example would involve a dictionary like this:

example_dict = {
    "Monday": ['a', 'b', 'c'],
    "Tuesday": ['d', 'e', 'f', 'g'],
    "Wednesday": ['h', 'i', 'j', 'k', 'l'],
    "Thursday": ['m'],
    "Friday": ['n', 'o', 'p', 'q'],
    "Saturday": ['r', 's', 't'],
    "Sunday": ['u', 'v', 'w', 'x', 'y', 'z']
}

From there you can iterate using a for loop and follow the index lookup with something like example_dict[x]. Here's the second part of your code refactored to show this:

name = input("Name: \n")

if len(name) > 0:
    for i in example_dict:
        # Lower case the letter for comparison
        if name[0].lower() in example_dict[i]:
            print(name   ", you should go to the hospital on "   i)

You can store lists in dictionaries! So once you've iterated the values it's just a matter of checking what day contains the letter of the name you're analyzing.

I hope this helps you get started.

CodePudding user response:

Dictionaries work by having keys corresponding to values, so if you do dict[key] or dict.get(key), you get the value.

The issue is that, with your scenario, it gets a little repetitive coding it.

letter_to_day = {
    'a':"Monday",
    'b':"Monday",
    'c':"Monday",
    'd':"Tuesday",
    ... # fair amount of typing
    'z':"Sunday"
}
name = input("Name: \n")

print(name   ", you should go to the hospital on "   letter_to_day[name[0].lower()])
#raises an error if it isn't a letter

print(name   ", you should go to the hospital on "   letter_to_day.get(name[0].lower(), "not a letter"))
#this one will return "not a letter" if it isn't found

But it turns out that there is an easier way - you can use inequalities with strings(and also lists, but that's not important).

Strings later alphabetically are greater, while strings earlier are lesser. "a" < "b" is True.

So that means you can do something like

def letter_to_day(letter):
    if "a" <= letter <= "c":
        return "Monday"
    elif "d" <= letter <= "g":
        return "Tuesday"
    elif "h" <= letter <= "l":
        return "Wednesday"
    elif letter == "m":
        return "Thursday"
    elif "n" <= letter <= "q":
        return "Friday"
    elif "r" <= letter <= "s":
        return "Saturday"
    elif "t" <= letter <= "z":
        return "Sunday"
    else:
        return "not a letter"

name = input("Name: \n")
print(name   ", you should go to the hospital on "   letter_to_day(name[0].lower()))

The answer on this post by iamwbj answers your question about having a dictionary that has days as its keys and lists of letters as its values. I think mine is faster, although it doesn't go in the direction you were expecting.

P.S. I wasn't sure if you actually meant Saturday R-S; Sunday: T-Z - your example code and question conflicted.

CodePudding user response:

tuple_letter = (['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j', 'k', 'l'], ['m'], ['n', 'o', 'p', 'q'], ['r', 's', 't'], ['u', 'v', 'w', 'x', 'y', 'z'])
tuple_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 
dictionary = dict(zip(tuple_week, tuple_letter))
print(dictionary)
name = input("Name: \n")
for key, value in dictionary.items():
  if name.lower()[0] in value:
    print(name.capitalize() , ", you should go to the hospital on " , key)
  1. Make Dict using inbuilt function and also more attention towards key and value pair
  2. You can input either in Upper case or lower case because during comparison it makes lower case then compare

CodePudding user response:

There two points you are missing:

  • the list index must be an integer
    • add the initial parameter like i to represent the index
    • use break to exit the for loop while check over
  • the name should be changed to lower case
    • add lower() to convert name[0]
tuple_letter = (['a', 'b', 'c'], ['d', 'e', 'f', 'g'], ['h', 'i', 'j', 'k', 'l'], ['m'], ['n', 'o', 'p', 'q'], ['r', 's', 't'], ['u', 'v', 'w', 'x', 'y', 'z'])
tuple_week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] 

name = input("Name: \n")
i = 0
for letters in tuple_letter:
    if letters.count(name[0].lower()) >= 1:
         print(name   ", you should go to the hospital on "   tuple_week[i])
         break
    i  = 1
  • Related