Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I write dict or {} in Python when constructing a dictionary with string keys?

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?

like image 952
Gurgeh Avatar asked Jun 14 '12 10:06

Gurgeh


4 Answers

{"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)
like image 187
Fred Foo Avatar answered Nov 08 '22 00:11

Fred Foo


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:

  • It looks less cluttered in some circumstances
  • It's 3 characters less per key-value pair
  • On keyboard layouts where { and } are awkward to type (AltGr-7 and AltGr-0 here) it's faster to type out
like image 30
Lauritz V. Thaulow Avatar answered Nov 08 '22 02:11

Lauritz V. Thaulow


Definitely, use {}, keep code simple & type less is always my target

like image 28
zinking Avatar answered Nov 08 '22 00:11

zinking


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().

like image 1
cdarke Avatar answered Nov 08 '22 02:11

cdarke