Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 532
daotoad Avatar asked Oct 02 '22 15:10

daotoad


People also ask

Is dict () and {} the same?

The setup is simple: the two different dictionaries - with dict() and {} - are set up with the same number of elements (x-axis). For the test, each possible combination for an update is run.

Is {} in Python a dict or set?

The fact that {} is used for an empty dictionary and not for an empty set has largely historical reasons. The syntax {'a': 100, 'b': 200} for dictionaries has been around since the beginning of Python. The syntax {1, 2, 3} for sets was introduced with Python 2.7.

How do you initialize a dictionary?

Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.

What is the use of dict () function?

The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.


2 Answers

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
like image 285
Wai Yip Tung Avatar answered Oct 19 '22 14:10

Wai Yip Tung


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',
)
like image 96
Amber Avatar answered Oct 19 '22 14:10

Amber