The difference between dictionary SetDefault and get methods in Python

Source: Internet
Author: User
The difference between setdefault and get methods in Python
d = {‘name‘:‘Liu‘, ‘sex‘:‘male‘}d.get(‘age‘, 15) # d 不变d.setdefault(‘age‘, 15) # d 增加一个键值对

Name implies

  • getMethod gets key A value of 15 when not being specified , it does not set the dictionary itself, but simply returns a specified value
  • setdefaultThe method is to set the unknown in the dictionary key value to the value we specify, when the value is not specified manually, None and it returns a reference to the specified value to the user, and if the value is a variable sequence, the sequence can be manipulated directly.
d = {}d.setdefault(‘list‘, []).append(‘10‘)

dThe value changes to

 {‘list‘: [‘10‘]}

The difference between dictionary SetDefault and get methods in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.