• Python: 3.8.11
  • OS: Ubuntu Kylin 20.04
  • Conda: 4.10.1
  • Jupyter lab: 3.1.4

code

my_dict = {'child': 'rat'.'ugly': 'cattle'.'Yin': 'the tiger'.'frame': 'rabbit'.'he': 'dragon'.'third': 'snakes'.'lunch': 'the horse'.'not': 'sheep'.'申': 'monkey'.The 'unitary': 'chicken'.'xu-gou': 'dog'.'hai': 'pig'}
Copy the code
If it cannot be found, it will be added.
# Obviously the key 'child' exists, so the value 'rat' is useless
my_dict.setdefault('child'.'is a rat')

'rat'
Copy the code
# return if found
my_dict.setdefault('child')

'rat'
Copy the code
If it cannot be found, it will be added.
my_dict.setdefault('Beginner's mind'.'the nuggets')
my_dict

{'child': 'rat'.'ugly': 'cattle'.'Yin': 'the tiger'.'frame': 'rabbit'.'he': 'dragon'.'third': 'snakes'.'lunch': 'the horse'.'not': 'sheep'.'申': 'monkey'.The 'unitary': 'chicken'.'xu-gou': 'dog'.'hai': 'pig'.'Beginner's mind': 'the nuggets'}
Copy the code
# nonexistent key "row", no value specified, default return None
print(my_dict.setdefault('row'))

None

Copy the code

Knowledge extension

help(dict.setdefault)


Help on method_descriptor:

setdefault(self, key, default=None, /)
    Insert key with a value of default if key is not in the dictionary.
    
    Return the value for key if key is in the dictionary, else default.

Copy the code

Learning to recommend

  • Python documentation – English
  • Python documentation – Chinese
  • Python code PEP
  • Google version of the Python specification
  • Python source code
  • Python PEP
  • Optimal kirin
  • The nuggets platform
  • Gitee platform


Python is open source, cross-platform, interpretive, interactive, and worth learning. Python’s design philosophy: elegant, unambiguous, simple. Advocate one way, preferably only one way to do one thing. Code should be written in accordance with specifications to facilitate communication and understanding. Every language has its own unique ideas. Beginners need to change their thinking, practice and accumulate.