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?
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.
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.
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.
The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.
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.
a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})
a = dict(import='trade', 1=7.8)
It will result in the following error:
a = dict(import='trade', 1=7.8)
^
SyntaxError: invalid syntax
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',
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With