1. b.93z.org
  2. Notes

dict() vs {}

The Performance Impact of Using dict() Instead of {} in CPython 2.7” article by Doug Hellmann made me recall why I don’t like to use dict when I can use {}. Actually, performance considerations (LOAD_NAME and CALL_FUNCTION versus *_MAP) have little to do with my syntactic preference.

You can’t override curly braces unless you know how to hack CPython and have some free time to waste. On the other hand, you can easily shadow dict just by naming something dict, so you need to check is it really reference to built-in class or not.

In Python ≤ 2.6, when you see { and }, you can always tell it’s dictionary. 2.7 and 3.* releases have set and dictionary comprehensions. That is, when you see { and }, it is either set or dict. If there is at least one colon, it is dictionary comprehension ({i: None for i in range(3)}) or just dictionary ({0: None, 1: None, 2: None}). Otherwise it is a mutable set (set or set comprehension):

>>> s1 = {'Hello', 'World'}
>>> type(s1)
<class 'set'>
>>> s2 = {i for i in range(3)}
>>> type(s2)
<class 'set'>

Of course, there are valid reasons to use class instead of literal. For instance, you can use it to merge two dicts or to create new dictionary (from old) with new values for some keys:

>>> d1 = {'a': 1, 'b': 2, 'c': 3}
>>> d1
{'a': 1, 'c': 3, 'b': 2}
>>> d2 = dict(d1, a=3, c=1)
>>> d2
{'a': 3, 'c': 1, 'b': 2}
>>> d3 = dict(d1, **{'d': 4, 'e': 5})
>>> d3
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}

My point is: dict() syntax does not make code “readable”. Do not abuse it.

© 2008–2017 93z.org