Inline dict manipulations
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
participants (1)
-
Tomasz Hławiczka