Is There a Difference Between Using a Dict Literal and a Dict Constructor

Is there a difference between using a dict literal and a dict constructor?

I think you have pointed out the most obvious difference. Apart from that,

the first doesn't need to lookup dict which should make it a tiny bit faster

the second looks up dict in locals() and then globals() and the finds the builtin, so you can switch the behaviour by defining a local called dict for example although I can't think of anywhere this would be a good idea apart from maybe when debugging

Why is the dict literal syntax preferred over the dict constructor?

The constructor is slower because it creates the object by calling the dict() function, whereas the compiler turns the dict literal into BUILD_MAP bytecode, saving the function call.

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

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

Why use dict() at all in Python?

The reason for the existence of dict(...) is that all classes need to have a constructor. Furthermore, it may be helpful if the constructor is able to take in data in a different format.

In your example use case, there is no benefit in using dict, because you can control the format the data is in. But consider if you have the data already as pairs in a list, the dict constructor may be useful. This can happen e.g. when reading lines from a file.

Is a dict literal containing repeated keys well-defined?

yes, it is well-defined -- last value wins. {0: 1, 0: 2} is a dictionary display:

If a comma-separated sequence of key/datum pairs is given, they are
evaluated from left to right to define the entries of the dictionary:
each key object is used as a key into the dictionary to store the
corresponding datum. This means that you can specify the same key
multiple times in the key/datum list, and the final dictionary’s value
for that key will be the last one given
.emphasis is mine



Related Topics



Leave a reply



Submit