I was looking for an algorithm, and I can\'t figure out why the dict d has values in it and curr does not. I think it does not seem like anything i
setdefault(key[, default)From the docs:
If
keyis in the dictionary, return its value. If not, insertkeywith a value ofdefaultand returndefault.defaultdefaults toNone.
Usage examples
>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> d.setdefault('a') # returns the corresponding value for key 'a'
1
>>> d.setdefault('a', 10) # returns the corresponding value for key 'a'
1
>>> d.setdefault('b') # returns the corresponding value for key 'b'
2
>>> d.setdefault('c', 100) # returns the corresponding value for key 'c'
3
>>> type(d.setdefault('z')) # because 'z' is not a key of d, None is returned which is the default value of default
>>> d.setdefault('z', 666) # returns 666 since key 'z' is not in d
666
I think you are confused because curr = curr.setdefault(letter, {}) always creates a new and empty dict, which is then assigned to curr. This means that instead of overwriting the values, you are adding a nesting level to the original dict for every element in words.
I also think that what you want to achieve with your code is to create a dictionary with every element in words as key with {} as value, so you can achieve it using the following code that uses a dict-comprehension:
def what(*words):
return {word: {} for word in set(words)}
Note: I have added the explanation of setdefault since your questions has been viewed particularly for this case, but I wanted to cover your specific question too.