'Calling function using the get operation from a dictionary

columnType and graphType are both dictionaries of functions. Can I call these using the get method?

columnType = {1: column_set1, 2: column_set2, 3: column_set3}
graphType = {1: graph_1, 2: graph_2, 3: graph_3, 4: graph_4, 5: graph_5, 6: graph_6}

# Enter column and graph type
columnInput = input("Enter column number: ")
graphInput = input("Enter graph number: ")

columnType.get(columnInput)
graphType.get(graphInput)

When I run it it does not print the graphs that are in the function.

def graph_6():
    unemployment = data[["States", "Region", "Estimated Unemployment Rate"]]
    figure = px.sunburst(unemployment,
                         path=["Region", "States"],
                         values="Estimated Unemployment Rate",
                         width=700,
                         height=700,
                         color_continuous_scale="RdY1Gn",
                         title="Unemployment Rate in India")
    figure.show()


Solution 1:[1]

Since your keys are ints, you'll need to convert the input() result to an int in order to look up the function, and then you'll need to use () to call the function:

graphType.get(int(graphInput))()

or more simply:

graphType[int(graphInput)]()

Note that if graphInput isn't a decimal string, this will raise ValueError, and if it's not present in the dictionary, using [] will raise KeyError. If you use get() to avoid the KeyError, you'll get a TypeError when you try to call the resulting None.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Samwise