# Creating a Python dict with the dict() syntax
Fri Jan 08 2021
Today I learned that you can create a dict
in Python using the
function-calling syntax:
dict(
key1=value1,
key2=value2
)
1
2
3
4
2
3
4
Contrast this to the usual way of creating a dict
:
{
"key1": value1,
"key2": value2
}
1
2
3
4
2
3
4
Where I'd like to start using the dict()
syntax more often is when I'll be
unpacking (opens new window)
the dict
as keyword arguments to a function. Why?
- It's easier to copy/cut and paste from method parameters.
- No need for typing out quotations around the keys.
- It's easier to read as method parameters. Like this:
d = dict(
param1=value1,
param2=value2
)
d['param3'] = value3
my_method(**d)
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
Newsletter
If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.