This might sound like a strange question, but bear with me…
I have a dictionary in Python with values like so:
'B': 23.6
'D': 0.6
'F': 35.9
'H': 35.9
I need to do an if-else with these values to do different things depending which one is > 30. The code I have at the moment is along the lines of:
if angles['B'] > 30:
# Do stuff
elif angles['D'] > 30:
# Do other stuff
elif angles['F'] > 30:
# Do different stuf
elif angles['H'] > 30:
# Do even more different stuff
Now the problem comes when I have two or more values the same (like in the example data above). In this case I want to randomly pick one of these to use. The question is: how do I do that in Python? Bear in mind that regardless of the values of the dictionary either nothing (if they’re all < 30) or only one thing should be done.
You can make a sequence of key/value pairs:
Filter it to remove elements <= 30:
check to see if there are any options
and then pick one:
update: added the following…
As Aaron mentions in the comments, this only gets you halfway there. You still need to codify the action you’re going to take based on
name.Aaron suggests using a dictionary containing functions. Basically, you would define some functions to do something with your name/value pairs
set up a dictionary mapping names to function calls
and define a routing function that dispatches to the appropriate function:
Then you can just call
routewith the name/value pair you get fromchoice, e.g.A more structured approach could instead involve creating a class to handle all of this or just the routing aspects.