Default dictionary syntax

Hi. I suggest a default syntax to define dictionary.

Example:

d1 = {'a':1, 'b':None, 'c':None}
d2 = {'a':1, 'b', 'c'}
d1 == d2

If key:value pair exists then it wont be set.

In addition to this, I suggest set methods in dict too.

Example:

d = {'a':1, 'b'}
d.add('c')
d -> {'a':1, 'b':None, 'c':None}

Why? What is the use case? We already have dict.get, collections.defaultdict, and set for set operations. What is this useful for?

3 Likes

This already exists as dict.fromkeys Built-in Types — Python 3.12.3 documentation

4 Likes

The suggestion saves a few characters, but it removes what is currently a useful self-explanatory SyntaxError:

>>> {'a':1, 'b'}
  File "<stdin>", line 1
    {'a':1, 'b'}
              ^
SyntaxError: ':' expected after dictionary key

and creates a new class of bug that is harder to diagnose.

The existing SyntaxError gives immediate* feedback to the coder, that they’ve forgotten to specify a value in a dict literal (or that a key/value pair has erroneously been added to a set literal). Under the suggestion, they’ve now got to wait until their program runs, possibly until after their code is shipped if the testing didn’t pick it up, to figure out there is a potentially much more devious bug, if a default value was unintentionally used in a dict literal, whether due to a typo or forgetfulness.

*it’s raised during parsing, not during execution.

4 Likes

{‘a’, ‘b’} is already legal syntax for a set. {‘a’, ‘b’: 3} looks like someone switched target in mid expression and should remain a syntax error.

5 Likes