Home > Backend Development > Python Tutorial > How to delete elements in python dictionary

How to delete elements in python dictionary

Release: 2019-07-06 09:04:35
Original
35487 people have browsed it

How to delete elements in python dictionary

1. The clear() method is used to clear all data in the dictionary. Because it is an in-situ operation, it returns None (which can also be understood as no return value)

>>> x['name'] = 'lili'
>>> x['age'] = 20
>>> x
{'age': 20, 'name': 'lili'}
>>> returned_value = x.clear()
>>> x
{ }
>>> print returned_value
None
Copy after login

What are the characteristics of the dictionary's clear() method:

>>> f = {'key':'value'}
>>> a = f
>>> a
{'key': 'value'}
>>> f.clear()
>>> f
{}
>>> a
{}
Copy after login

When the original dictionary is referenced, if you want to clear the elements in the original dictionary, use the clear() method, and the elements in the dictionary will also be cleared at the same time. .

The Python dictionary pop() method deletes the given key key and the corresponding value in the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, return the default value.

2. Pop() method syntax:

pop(key[,default])
Copy after login

Parameters:

key: the key value to be deleted default: If there is no key, return the default value

Return value: Return the deleted value.

Example:

>>> x = {'a':1,'b':2}
>>> x.pop('a')
1
>>> x
{'b': 2}
Copy after login

3. The function of the dictionary popitem() method is to randomly return and delete a pair of keys and values ​​(items) in the dictionary.

>>> x
{'url': 'www.iplaypy.com', 'title': 'python web site'}
>>> x.popitem()
('url', 'www.iplaypy.com')
>>> x
{'title': 'python web site'}
Copy after login

4. The del method can delete a single element and clear the dictionary. Clearing only requires one operation.

#!/usr/bin/python
# -*- coding: UTF-8 -*-
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']  # 删除键是'Name'的条目
del dict          # 删除字典
Copy after login

For more Python-related technical articles, please visit the Python Tutorial column to learn!


The above is the detailed content of How to delete elements in python dictionary. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template