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

This is just a trivial question about what you are offering. Recently, I saw many examples of people writing dict(key1=val1, key2=val2) instead of what, in my opinion, is more idiomatic {"key1": val1, "key2": val2} . I think the reason is not to use "" for keys, but I'm not sure. Perhaps dict() -syntax looks closer to other languages?

+6
source share
4 answers

I am going to go against the stream here:

Use the dict() method if it suits you, but keep the limitations outlined in other answers. There are some advantages to this method:

  • In some cases, it looks less cluttered.
  • This is at least 3 characters per key pair.
  • On layouts where { and } inconvenient to type (AltGr-7 and AltGr-0 here), it’s faster to type
+5
source

{"key1": val1, "key2": val2} more idiomatic; I almost never came across a dict with keyword arguments, and of course I was never tempted to write it. This is also more general because keyword arguments must 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) 
+8
source

Definitely use {}, keep the code simple and enter less is always my goal

+2
source

There is some ambiguity with curly braces {}. Consider:

 >>> x = {'one','two','three'} >>> type(x) <type 'set'> >>> x = {} >>> type(x) <type 'dict'> 

If there is no ambiguity when using set() or dict() .

+1
source

Source: https://habr.com/ru/post/918079/


All Articles