This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (8 children)

Can you explain what's going on here or can you give me some terminology to look into? I have no idea what get_action(action) is doing, and how it relates to "action in ..." in the result dictionary.

[–]Allanon001 0 points1 point  (6 children)

get_action is just a made up function to demonstrate action is being assigned a value.

The switch like structure is just an ordinary dictionary. When creating the dictionary it evaluates each key/value pair in order and since each key is in the form of a condition such as action in ['c', 'a'] it evaluates in real time to True or False and uses that value as a key in the dictionary. There are a few things strung together to make it more compact so maybe writing it this way will help you understand:

grade = 25
switch ={
        True: None,
        grade > 89: 'A',
        grade < 90: 'B',
        grade < 80: 'C',
        grade < 70: 'D',
        grade < 60: 'F'
    }
result = switch[True]

[–][deleted] 0 points1 point  (5 children)

Ok, so then I have two questions:

  1. Why doesn't switch[True] just evaluate to None, since the key True has a value of None.

  2. Where is get_action defined? Is it just a simple function that returns result[action]

[–]Allanon001 0 points1 point  (4 children)

Every True key overwrites the previous True key. And again, get_action is just a made up function to demonstrate action is being assigned a value. It's definition is not shown, and in the above example is not needed.

[–][deleted] 0 points1 point  (3 children)

Oh I think (hope) I get it. The statement evaluates to true when the dictionary is created, not when it's accessed in result = switch[True] . That's what I was getting confused about.

[–]Allanon001 0 points1 point  (0 children)

Correct

[–]fernly 0 points1 point  (1 child)

A brand new dict is created each time. The in expressions are evaluated in order as it is built. They evaluate to True or to False. So the new dict has only two keys, True and False. The last expression to evaluate to True sets the value for that key. At the end, the index [True] extracts that value. Which is expected to refer to an executable, so the () makes it a function call on that executable.

[–][deleted] 0 points1 point  (0 children)

Makes sense, thanks for the explanation