Hello,

This is my first mail here, so greetings for everyone :)

I would like to introduce an idea of the new operators for dict objects.
Any thoughts are welcome.

Since Python3.9 there is a great feature for merging dicts using | (OR) 
operator:
{1: "a"} | {2: "b"} == {1: "a", 2: "b"}

Thus, this basic operation can be done smoothly (also inline).
PEP: https://www.python.org/dev/peps/pep-0584/


Another common operation on dicts is a substitution - building a new dict with 
only a part of the data. Usually the part of the data is described as a list 
of keys to keep or a list of keys to skip.

Therefore it would be very handy to have a build-in option to filter out a 
dict with a similar fashion, for example using & (AND) operator against a 
list/tuple/set/frozenset of keys that should be kept in the result):
{1: "a", 2: "b", 3: "c"} & [1, 3, 4] == {1: "a", 3: "c"}
{1: "a", 2: "b", 3: "c"} & {1, 3, 4} == {1: "a", 3: "c"}

Using the & operator:
 dict_object & list_of_keys
would be equal to the following expression:
 {key: value for key, value in dict_object .items() if key in list_of_keys}

Additionally, a similar option for omitting specified keys could be done with 
another - (minus) operator against a list/tuple/set/frozenset of keys that 
should be suppressed):
{1: "a", 2: "b", 3: "c"} - [3, 4] == {1: "a", 2: "b"}
{1: "a", 2: "b", 3: "c"} - {3, 4} == {1: "a", 2: "b"}

Using the - operator:
 dict_object - list_of_keys
would be equal to following expression:
 {key: value for key, value in dict_object .items() if key not in 
list_of_keys}


Best,
 Tomasz

_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/7GXACFF4L6Y24VK6OIM7ETJJMDPO2KFC/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to