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


Question

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.

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?

1
196
12/21/2014 10:48:01 AM

Accepted Answer

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.

In other words it cannot do:

a = {'import': 'trade', 1: 7.8}
221
8/6/2015 6:34:38 PM

The first, curly braces. Otherwise, you run into consistency issues with keys that have odd characters in them, like =.

# Works fine.
a = {
    'a': 'value',
    'b=c': 'value',
}

# Eeep! Breaks if trying to be consistent.
b = dict( 
    a='value',
    b=c='value',
)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon