Search code examples
pythondictionaryplotlyconventions

Is there a convention in using dict vs curly brace initialisation when using Plotly?


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


Solution

  • 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}.