If / else for statements

If I were to write an instruction using a dictionary instead of an else statement, how would it be? For example, let's say I have

def determineRank(years): if years == 1: return "Freshman" elif years == 2: return "Sophmore" elif years == 3: return "Junior" else: return "Senior" 

If I were to rewrite this dictionary, it would be

 rank = {"Freshman":1, "Sophmore":2, "Junior":3, "Senior", ???} 

what number will I write for another?

+5
source share
3 answers

Use the .get method with a default value as the second argument:

 rank = {1: 'Freshman', 2: 'Sophmore', 3: 'Junior'} rank.get(years, 'Senior') 
+5
source

You can use dictObject.get(key, defaultValue) .

So, the equivalent of your function would be:

 rank = {1: "Freshman", 2: "Sophmore", 3:"Junior"}.get(year, "Senior"); 

Note that dictionary key / value pairs are canceled.

+3
source

To expand on what has already been posted here, using dict.get will not raise KeyError when a key, for example. "Elder" is not yet in the dictionary.

You can also do something similar using the ternary operator to check if a given year is the key in rank :

 rank = {1: "Freshman", 2: "Sophomore", 3: "Junior"} year = 4 year_rank = rank[year] if year in rank else "Senior" 

year_rank will be senior

I think the dict.get method dict.get little better.

+1
source

Source: https://habr.com/ru/post/1266773/


All Articles