Is there a difference between using a Python dictionary literal and a dictionary constructor?

Is there a difference between using a Python dictionary literal and a dictionary constructor?

While using PyCharm, I noticed it offers to convert a dictionary literal:

d = {
'one': '1',
'two': '2',
}

into a dictionary constructor:

d = dict(one='1', two='2')

Do these different approaches differ in any significant way?

While writing this question, I noticed that using dict() it seems impossible to specify a numeric key, for example, d = {1: 'one', 2: 'two'} is possible, but dict(1='one', 2='two') is not. Are there any other differences?

The primary difference you’ve highlighted is correct. The Python dictionary literal is generally faster because it doesn’t require a lookup for the dict constructor.

Here are a few more points to consider:

  • Performance: The dictionary literal ({}) is a direct way to create a dictionary, and doesn’t require looking up the dict function, making it marginally faster than the dict() constructor in most cases.

  • Flexibility: The dict() constructor allows you to create dictionaries with dynamic keys, such as when using keyword arguments (dict(a=1, b=2)), which can be useful in certain scenarios, particularly when generating keys programmatically.

  • Customizing Behavior: The dict() constructor can also be overridden by defining a local variable named dict. This allows you to modify its behavior for specific use cases, although this is not a common practice unless you’re debugging or exploring alternative behavior.

Instead of using a literal or the constructor, you can use a comprehension to dynamically generate a dictionary.

For example:

d = {key: value for key, value in zip(range(5), ['a', 'b', 'c', 'd', 'e'])}