python dict setdefault, confused

后端 未结 3 993
一生所求
一生所求 2020-12-19 03:09

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

3条回答
  •  佛祖请我去吃肉
    2020-12-19 03:27

    setdefault(key[, default)

    From the docs:

    If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

    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
    

    In your code

    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.

提交回复
热议问题