0

The docs for Plotly and many answers on Stack Overflow trend toward using

dict(foo=bar)

instead of

{'foo':'bar'}

Is there a particular reason for this preference? I've been told in the past that curly brace initialisation is preferred.


Some examples pulled randomly:

Plotly multi axis docs
Plotly multi axis docs

Adding secondary y axis to bar line chart in ploty express
Adding secondary y axis to bar line chart in ploty express

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • 3
    Both of these are really just matters of opinion. The *literal* form will be faster, although that isn't usually a concern. It also accepts any kind of keys instead of just string keys – juanpa.arrivillaga Mar 05 '22 at 01:57
  • 2
    Does this answer your question? [Is there a difference between using a dict literal and a dict constructor?](https://stackoverflow.com/questions/6610606/is-there-a-difference-between-using-a-dict-literal-and-a-dict-constructor) (Although you mention plotly, this isn't specific to plotly, as both return a dict) – Gino Mempin Mar 05 '22 at 02:08

1 Answers1

4

Python's naming convention

One reason why dict(foo=bar) may be preferred to {'foo':'bar'}:

In {'foo':'bar'}, the key foo can be initialized to be any string. For example,

mydict = {'1+1=':2}

is allowed.

dict(foo=bar) ensures the dictionary keys to be valid identifiers. For example,

mydict = dict('1+1='=2)

will return error SyntaxError: keyword can't be an expression.

Non-string key

The second reason may be when you want the key to be not a string. For example, dict(a = 2) is allowed, but {a: 2} is not. You would want {'a': 2}.

Ka Wa Yip
  • 2,546
  • 3
  • 22
  • 35