0

In Python 2.7.15:

>>> dict((s, len(s)) for s in ['aa', 'b', 'cccc'])
{'aa': 2, 'cccc': 4, 'b': 1}

>>> {(s, len(s)) for s in ['aa', 'b', 'cccc']}
set([('b', 1), ('aa', 2), ('cccc', 4)])

Why does dict() create a dictionary, but {} creates a set? I thought those two syntaxes were synonymous.

Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
  • By using dict you are specifying the key:value pair when doing the list comprehension, whereas when using the {} is naming elements within that set which are not necessarily key:value pairs. [This Answer](https://stackoverflow.com/questions/34370599/difference-between-dict-and-set-python) goes into more detail about why that is the case. – Edeki Okoh Feb 14 '19 at 17:09
  • Possible duplicate of [Difference between dict and set (python)](https://stackoverflow.com/questions/34370599/difference-between-dict-and-set-python) – Edeki Okoh Feb 14 '19 at 17:10

0 Answers0