This is just a trivial question of what convention you suggest. Recently, I have seen many examples of people writing dict(key1=val1, key2=val2)
instead of what I think is the more idiomatic {"key1": val1, "key2": val2}
. I think the reason is to avoid using ""
for the keys, but I am not sure. Perhaps the dict()
-syntax looks closer to other languages?
{"key1": val1, "key2": val2}
is more idiomatic; I hardly ever encounter dict
with keyword arguments and I've certainly never been tempted to write it. It's also more general, because keyword arguments have to be Python identifiers:
>>> {"foo bar": 1}
{'foo bar': 1}
>>> dict(foo bar=1)
------------------------------------------------------------
File "<ipython console>", line 1
dict(foo bar=1)
^
SyntaxError: invalid syntax
>>> dict("foo bar"=1)
------------------------------------------------------------
File "<ipython console>", line 1
SyntaxError: keyword can't be an expression (<ipython console>, line 1)
I'm going to go against the flow here:
Use the dict()
method if it suits you, but keep the limitations outlined in other answers in mind. There are some advantages to this method:
{
and }
are awkward to type (AltGr-7 and AltGr-0 here) it's faster to type outDefinitely, use {}, keep code simple & type less is always my target
There is some ambiguity with the braces { }. Consider:
>>> x = {'one','two','three'}
>>> type(x)
<type 'set'>
>>> x = {}
>>> type(x)
<type 'dict'>
Whereas there is no ambiguity with using set()
or dict()
.
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