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.

Answer from Martijn Pieters on Stack Exchange
🌐
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 ... Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-dictionary-methods
Python Dictionary Methods - GeeksforGeeks
Python dictionary methods is collection of Python functions that operates on Dictionary. Python Dictionary is like a map that is used to store data in the form of a key: value pair. Python provides various built-in functions to deal with dictionaries.
Published   July 23, 2025
Discussions

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
python - Using a dictionary to select function to execute - Stack Overflow
The final users are sellers, people ... wanted a python based one, so yeah, the user can modify the dictionary in a single buggy line and the product won't work, so yes, they just need to restart but the costumer will complain. 2012-02-06T23:34:15.443Z+00:00 ... @JonnyDH Your arguments don't really make sense. "With a single buggy line" they can clobber your main function just as easily ... 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
4
0
February 11, 2023
Is putting functions in dictionaries is good? and if not then why my functions run before call its key value?
Putting functions in dictionaries is fine. But you 're not doing that, you're putting the results of the functions in the dictionary, because you're calling it when you define the dict. Instead, actually put the functions there: dict = { 'hello': hello, # no parentheses 'bye': bye } and call them when you need to: func = dict[key_phrase] func() More on reddit.com
🌐 r/learnpython
18
16
January 29, 2024
🌐
freeCodeCamp
freecodecamp.org › news › python-dictionary-methods-dictionaries-in-python
Python Dictionary Methods – Dictionaries in Python
July 28, 2022 - The popitem() method works like the pop() method. The difference is that it removes the last item in the dictionary.
🌐
Mimo
mimo.org › glossary › python › dictionary-dict-function
Python Dictionary: Syntax and Examples [Python Tutorial]
In Python, you can create dictionaries with default values for all keys, which is useful when you need data structures with predictable defaults. You can use the built-in function fromkeys() to create a new dictionary where each key from a collection (e.g., a list) gets the same default value.
🌐
Python documentation
docs.python.org › 3 › tutorial › datastructures.html
5. Data Structures — Python 3.14.4 documentation
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated ...
🌐
Programiz
programiz.com › python-programming › methods › dictionary
Python Dictionary Methods | Programiz
Dictionaries in Python Start Learning Python · Add two numbers · Check prime number · Find the factorial of a number · Print the Fibonacci sequence · Check leap year Explore Python Examples · Built-in Functions · List Methods · Dictionary Methods · String Methods View all ·
🌐
Real Python
realpython.com › python-dicts
Dictionaries in Python – Real Python
2 weeks ago - 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
🌐
Tutorial Teacher
tutorialsteacher.com › python › dictionary-methods
Built-in Dictionary Functions in Python
The following table lists all the functions that can be used with the Dictionary type in Python 3.
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

🌐
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.
🌐
W3Schools
w3schools.com › python › python_dictionaries.asp
Python Dictionaries
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 ... Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts
🌐
Cisco
ipcisco.com › home › python dictionary methods
Python Dictionary Methods with Examples | get, keys, values, items
April 3, 2021 - Now, let’s focus these python dictionary methods and learn them one by one. ... get() method is used to get the value of a given key. As you know there are key:value pair in python dictionaries.
🌐
PrepBytes
prepbytes.com › home › python › dictionary functions in python
Dictionary Functions in Python
November 29, 2023 - Dictionary functions in Python play a pivotal role in performing various operations on dictionaries, such as adding or removing elements, accessing values, iterating through items, and more.
🌐
DataFlair
data-flair.training › blogs › python-dictionary
Python Dictionary with Methods, Functions and Dictionary Operations - DataFlair
July 22, 2025 - It isn’t necessary to use the same kind of keys (or values) for a dictionary in Python. ... As you can see here, a key or a value can be anything from an integer to a list. Using the dict() function, you can convert a compatible combination of constructs into a Python dictionary.
🌐
W3Schools
w3schools.com › python › ref_func_dict.asp
Python dict() Function
Python Examples Python Compiler ... Interview Q&A Python Bootcamp Python Certificate Python Training ... The dict() function creates a dictionary....
🌐
Studytonight
studytonight.com › python › functions-for-dictionary
Dictionary Functions in Python
As you might have already guessed, it gives the number of elements stored in the dictionary or you can say just the number of keys in it. ... If we ever need to delete all elements of the dictionary using the del keyword, for each key value, that would be quite troublesome. Hence clear() function makes emptying a dictionary, a single line task.