4 ways to remove a dictionary element from Python __python

Source: Internet
Author: User
Tags delete key

1. The clear () method of the Python dictionary (delete all elements in the dictionary)

#!/usr/bin/python
#-*-coding:utf-8-*-
dict = {' name ': ' My blog address ', ' Alexa ': 10000, ' url ': ' http://blog.csdn.net/ uuihoo/'}
dict.clear ();  # Empty Dictionary all entries

2. The pop () method of the Python dictionary (deletes the value of the dictionary given key keys and returns the value to be deleted)

#!/usr/bin/python
#-*-coding:utf-8-*-
site= {' name ': ' My blog address ', ' Alexa ': 10000, ' url ': ' http://blog.csdn.net/ uuihoo/'}
pop_obj=site.pop (' name ') # Delete key value pairs that you want to delete, such as {' name ': ' My blog address '} This key value to
print pop_obj   # output: my blog address

3. Popitem () method of the Python dictionary (randomly returns and deletes a pair of keys and values in the dictionary)

#!/usr/bin/python
#-*-coding:utf-8-*-
site= {' name ': ' My blog address ', ' Alexa ': 10000, ' url ': ' Http://blog.csdn.net /uuihoo/'}
Pop_obj=site.popitem () # randomly returns and deletes a key value pair of
print pop_obj   # output may be {' url ', ' http:// blog.csdn.net/uuihoo/'}

4. Del Global method (can delete a single element can also empty the dictionary, empty only one operation)

#!/usr/bin/python
#-*-coding:utf-8-*-
site= {' name ': ' My blog address ', ' Alexa ': 10000, ' url ': ' http://blog.csdn.net/ uuihoo/'}
del site[' name ' # Delete key is ' name ' entry 
del site  # empty dictionary all entries

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.