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 Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-dict-function
Python dict() Function - GeeksforGeeks
July 23, 2025 - dict() function in Python is a built-in constructor used to create dictionaries. A dictionary is a mutable, unordered collection of key-value pairs, where each key is unique.
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ tutorial โ€บ datastructures.html
5. Data Structures โ€” Python 3.14.3 documentation
A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
Discussions

python - Using dict() function to create a dictionary object? - Stack Overflow
I am able to create the dictionary object as follows: a = dict(name='John', country='Norway') The gives an output as: {'name': 'John', 'country': 'Norway'} However, the following statement is thro... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Dictionary functions
I think it should be added a function of append() in ditionary :smiley: More on discuss.python.org
๐ŸŒ discuss.python.org
0
February 11, 2023
Syntax Help: dict[function]()
demo_name is just a string. How would you get a function from just a string? The dictionary is there since here, it maps strings to functions. Why not just [demo_name]() as the last line? Because that doesn't make sense if you think about it. [demo_name] is a list containing a single element: the demo_name string. () after the ] then attempts to call that list as a function, which will fail because lists don't support that. More on reddit.com
๐ŸŒ r/learnpython
8
2
October 12, 2023
syntax - Why store a function inside a python dictionary? - Software Engineering Stack Exchange
I'm a python beginner, and I just learned a technique involving dictionaries and functions. The syntax is easy and it seems like a trivial thing, but my python senses are tingling. Something tells me this is a deep and very pythonic concept and I'm not quite grasping its importance. More on softwareengineering.stackexchange.com
๐ŸŒ softwareengineering.stackexchange.com
January 9, 2013
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ ref_func_dict.asp
Python dict() Function
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... The dict() function creates a dictionary.
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_ref_dictionary.asp
Python Dictionary Methods
Python Dictionaries Access Items Change Items Add Items Remove Items Loop Dictionaries Copy Dictionaries Nested Dictionaries Dictionary Methods Dictionary Exercises Code Challenge Python If...Else ยท Python If Python Elif Python Else Shorthand If Logical Operators Nested If Pass Statement Code Challenge Python Match ... Python Functions Python Arguments Python *args / **kwargs Python Scope Python Decorators Python Lambda Python Recursion Python Generators Code Challenge Python Range
๐ŸŒ
Real Python
realpython.com โ€บ python-dicts
Dictionaries in Python โ€“ Real Python
December 16, 2024 - Learning about them is essential for developers who want to process data efficiently. In this tutorial, youโ€™ll explore how to create dictionaries using literals and the dict() constructor, as well as how to use Pythonโ€™s operators and built-in functions to manipulate them.
Find elsewhere
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
Dictionary functions - Python Help - Discussions on Python.org
February 11, 2023 - I think it should be added a function of append() in ditionary ๐Ÿ˜ƒ
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ syntax help: dict[function]()
r/learnpython on Reddit: Syntax Help: dict[function]()
October 12, 2023 -

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

Top answer
1 of 5
120

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.

2 of 5
36

@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
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ is putting functions in dictionaries is good? and if not then why my functions run before call its key value?
r/learnpython on Reddit: Is putting functions in dictionaries is good? and if not then why my functions run before call its key value?
January 29, 2024 -

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

๐ŸŒ
Mimo
mimo.org โ€บ glossary โ€บ python โ€บ dictionary-dict-function
Mimo: The coding platform you need to learn Web Development, Python, and more.
You create a dictionary using curly braces {} with keys and values separated by a colon :. ... Become a Python developer. Master Python from basics to advanced topics, including data structures, functions, classes, and error handling
๐ŸŒ
Google
developers.google.com โ€บ google for education โ€บ python โ€บ python dict and file
Python Dict and File | Python Education | Google for Developers
The methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ c-api โ€บ dict.html
Dictionary Objects โ€” Python 3.14.3 documentation
2 weeks ago - If result is not NULL, then *result is set to a strong reference to either default_value, if the key was not present, or the existing value, if key was already present in the dictionary. Returns 1 if the key was present and default_value was not inserted, or 0 if the key was not present and default_value was inserted. On failure, returns -1, sets an exception, and sets *result to NULL. For clarity: if you have a strong reference to default_value before calling this function, then after it returns, you hold a strong reference to both default_value and *result (if itโ€™s not NULL).
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ collections.html
collections โ€” Container datatypes
Return a new dictionary-like object. defaultdict is a subclass of the built-in dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ home โ€บ python โ€บ python dict() function
Python dict() Function
February 21, 2009 - The Python dict() function is used to create a new dictionary. A dictionary is a data structure that stores a collection of key-value pairs. Each key in the dictionary is unique and maps to a specific value.
๐ŸŒ
Simplilearn
simplilearn.com โ€บ home โ€บ resources โ€บ software development โ€บ python dictionary guide: what it is & how to create one
Python Dictionary Guide: What It Is & How to Create One
2 weeks ago - Learn what a dictionary is in Python and how to create one. Discover essential tips for managing key-value pairs in Python dictionaries efficiently.
Address ย  5851 Legacy Circle, 6th Floor, Plano, TX 75024 United States
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-dictionary-methods
Python Dictionary Methods - GeeksforGeeks
Python dictionary methods is collection of Python functions that operates on Dictionary.
Published ย  July 23, 2025