Python dictionary addition and deletion operations

Source: Internet
Author: User

The Python programming language is a general computer language that is easy to learn. For beginners, some basic applications must be mastered first. For example, the operations related to the Python dictionary we introduced to you today are the skills we need to master in the learning process.

Python Dictionary (Dictionary) is a data type of the ing structure, which consists of unordered "key-value pairs. The dictionary key must be of unchangeable type, such as string, number, and tuple. The value can be of any Python data type.

1. Create a Python dictionary

 
 
  1. >>> Dict1 ={}# create an empty dictionary
  2. >>> Type (dict1)
  3. <Type 'dict '>

2. Add Python dictionary elements: Two Methods

 
 
  1. >>> Dict1 ['a'] = 1 # first
  2. >>> Dict1
  3. {'A': 1}
  4. # Method 2: setdefault
  5. >>> Dict1.setdefault ('B', 2)
  6. 2
  7. >>> Dict1
  8. {'A': 1, 'B': 2}

3. Delete the Python dictionary

 
 
  1. # Deleting a specified key-Value Pair
  2. >>> Dict1
  3. {'A': 1, 'B': 2}
  4. >>> Del dict1 ['a'] # You can also use the pop method, dict1.pop ('A ')
  5. >>> Dict1
  6. {'B': 2}
  7. # Clearing the dictionary
  8. >>> Dict1.clear ()
  9. >>> Dict1 # The dictionary is empty.
  10. {}
  11. # Deleting dictionary objects
  12. >>> Del dict1
  13. >>> Dict1
  14. Traceback (most recent call last ):
  15. File "<interactive input>", line 1, in <module>
  16. NameError: name 'dict1' is not defined

The above is an introduction to the Python dictionary.

Related Article

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.