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

Viewed 156545

Using PyCharm, I noticed it offers to convert a dict literal:

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

into a dict constructor:

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

Do these different approaches differ in some significant way?

(While writing this question I noticed that using dict() it seems impossible to specify a numeric key .. d = {1: 'one', 2: 'two'} is possible, but, obviously, dict(1='one' ...) is not. Anything else?)

12 Answers

There is no dict literal to create dict-inherited classes, custom dict classes with additional methods. In such case custom dict class constructor should be used, for example:

class NestedDict(dict):

    # ... skipped

state_type_map = NestedDict(**{
    'owns': 'Another',
    'uses': 'Another',
})

Super late to the party here, but if you have a kwargs function:

def foo(a=None, b=None):
    ...

And your splatting a dict like so:

d_1 = { 'a': 1, 'b': 2 }
d_2 = dict(a=1, b=2)

# This works
foo(**d_1)

# And this as well
foo(**d_2)

But d_2 may be better suited for refactoring argument names that may change in your foo signature. Since in d_1 they are strings.

Also, when it comes to reading code (which is a lot), I feel that the literal has less cognitive burden (because we associate literals to be something that is less "active" than say a dict() which looks like a function call which makes the brain wonder...at least for a micro second :)) compared to dict(), admittedly partly due to the syntax highlighting in the editor, but still very relevant on a daily basis (at least for me).

If I focus on the surrounding code around the dict statement represented as ..., a literal dict makes it a bit easier for me to understand the surrounding code :).

...
...
...
config = {
    'key1':"value1",
    'key2':"value2",
    'key3':"value3",
    'key4':"value4",
}
...
...
...

#****VS *****

...
...
...
config =dict(
    key1 = 'value1',
    key2 = 'value2',
    key3 = 'value3',
    key4 = 'value4',

)
...
...
...

Related