Skip to content
Advertisement

How to chain Python’s set.add() while updating dictionary values being sets?

Let’s create dictionary dctD entries with values being set()s:

JavaScript

Now the dictionary has to be updated with a new value which should extend its set() value if the at runtime unknown key value is already in the dictionary:

JavaScript

The GOAL is to extend the set being value in dctD by a value also in case the key does not yet exist. Because the set.add() method does not return the with the new value updated set a tmpSet identifier is required to achieve such goal. The code for extending existing or creating new set is then:

JavaScript

With help of the walrus operator it is possible to cut down the code above to two lines of code as follows:

JavaScript

And with help of a chainOfSet class as a wrapper for the set() methods to one line (with improved readability):

JavaScript

Now the question:

Does Python allow a simpler way to code the above one-line assignment without the need of writing a wrapper class?

Below the code of the chainOfSet class and all of the code mentioned above:

JavaScript

Notice that above provided wrapper class allows not only chaining, but also usage of the addition operator:

JavaScript

printing as output

JavaScript

Update: evolution of code improvements in 4 steps:

All of the 4 steps produce the same result, so the code below runs without assertion error. Notice how it was possible to get the lines and code length in characters down using the different approaches:

JavaScript

Advertisement

Answer

From what I can understand, this can easily be done with a defaultdict

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement