# Creating a Python dict with the dict() syntax

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

Contrast this to the usual way of creating a dict:

{
  "key1": value1,
  "key2": value2
}
1
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?

  1. It's easier to copy/cut and paste from method parameters.
  2. No need for typing out quotations around the keys.
  3. 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

Newsletter

If you'd like to subscribe to my blog, please enter your details below. You can unsubscribe at any time.

Powered by Buttondown.

Last Updated: 11/20/2023, 10:04:51 AM