Well...
For the first example, this is how it's done:
def dummydict(**kwargs):
return kwargs
>>> dummydict(a=1, b=2, c=4)
{'a': 1, 'b': 2, 'c': 4}
>>>
As you can see, **kwargs unpacks the keyword arguments into a dictionary, that's why it works.
As mentioned in the documentation:
**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.
For why the second example doesn't work, it is because it gets treated as a variable name, the second one isn't named arguments, it's only tuples in a list, you would have to do:
dict([('name', 'John'), ('country', 'Norway')])
Answer from U13-Forward on Stack Overflowpython - Using dict() function to create a dictionary object? - Stack Overflow
Dictionary functions
Syntax Help: dict[function]()
syntax - Why store a function inside a python dictionary? - Software Engineering Stack Exchange
Videos
I saw this here:
https://docs.streamlit.io/library/get-started/multipage-apps/create-a-multipage-app
In the beginning of this tutorial for Streamlit, if you expand hello.py the last few lines are:
page_names_to_funcs = {
"โ": intro,
"Plotting Demo": plotting_demo,
"Mapping Demo": mapping_demo,
"DataFrame Demo": data_frame_demo
}
demo_name = st.sidebar.selectbox("Choose a demo", page_names_to_funcs.keys())
page_names_to_funcs[demo_name]() I can see that when an option is chosen in the selectbox, it assigns the related value to demo_name. Then it calls a function by that name. But what is this syntax on the last line? Is there a name for this type of invocation?
The Values assigned to each key in the dict have a corresponding function with the same name above it elsewhere in the code.
I can of course tell that [demo_name] references the value and parens() indicate it is a function being called. But why does it even have page_names_to_funcs in that last line, when that dict is no longer needed to reference the value in demo_name? Why not just [demo_name]() as the last line?
thanks
Using a dict let's you translate the key into a callable. The key doesn't need to be hardcoded though, as in your example.
Usually, this is a form of caller dispatch, where you use the value of a variable to connect to a function. Say a network process sends you command codes, a dispatch mapping lets you translate the command codes easily into executable code:
def do_ping(self, arg):
return 'Pong, {0}!'.format(arg)
def do_ls(self, arg):
return '\n'.join(os.listdir(arg))
dispatch = {
'ping': do_ping,
'ls': do_ls,
}
def process_network_command(command, arg):
send(dispatchcommand)
Note that what function we call now depends entirely on what the value is of command. The key doesn't have to match either; it doesn't even have to be a string, you could use anything that can be used as a key, and fits your specific application.
Using a dispatch method is safer than other techniques, such as eval(), as it limits the commands allowable to what you defined beforehand. No attacker is going to sneak a ls)"; DROP TABLE Students; -- injection past a dispatch table, for example.
@Martijn Pieters did a good job explaining the technique, but I wanted to clarify something from your question.
The important thing to know is that you are NOT storing "the name of the function" in the dictionary. You are storing a reference to the function itself. You can see this using a print on the function.
>>> def f():
... print 1
...
>>> print f
<function f at 0xb721c1b4>
f is just a variable that references the function you defined. Using a dictionary allows you to group like things, but it isn't any different from assigning a function to a different variable.
>>> a = f
>>> a
<function f at 0xb721c3ac>
>>> a()
1
Similarly, you can pass a function as an argument.
>>> def c(func):
... func()
...
>>> c(f)
1
Hi, i am new to python and following the book by Al-Sweigart-Automate-The-Boring-Stuff-With-Python and i just finished the Project: Multi-Clipboard Automatic Messages of chapter 6 where author puts strings in keys like this :
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next week?""",
'upsell': """Would you consider making this a monthly donation?"""so i decided to put functions as key values but the functions in dictionaries execute before i call the key values:
def hello():
print('Hello')
def bye():
print('Bye!')
dict = {'hello': hello(),
'bye': bye()
}
key_phrase = str(input('Enter the key: '))
if key_phrase in dict:
print(f'Function for {key_phrase} has been called')
else:
print(f'No key named {key_phrase} in the dict ')please help me
I was wondering is there anyway in python that when I create a dictionary in python say
calculations = {"add":add(),"subtract":subtract(),"multiple":multiply()}
that it only calls the functions when I do something like
calculations["add"] instead of calling all the functions initially when the code runs