What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

daotoad picture daotoad · May 18, 2010 · Viewed 348.3k times · Source

I'm putting in some effort to learn Python, and I am paying close attention to common coding standards. This may seem like a pointlessly nit-picky question, but I am trying to focus on best-practices as I learn, so I don't have to unlearn any 'bad' habits later.

I see two common methods for initializing a dict:

a = {
    'a': 'value',
    'another': 'value',
}

b = dict( 
    a='value',
    another='value',
)

Which is considered to be "more pythonic"? Which do you use? Why?

Answer

Wai Yip Tung picture Wai Yip Tung · May 18, 2010

Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won't work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
             ^
SyntaxError: invalid syntax