Python dictionary adds a method to delete key values

爱喝马黛茶的安东尼
Release: 2019-06-17 16:43:47
Original
8042 people have browsed it

How to add and delete key values ​​in python dictionary?

Related recommendations: "python Video"

Python dictionary adds a method to delete key values

Python dictionary (Dictionary) is a data type of mapping structure, consisting of no It consists of sequential "key-value pairs". The keys of the dictionary must be of immutable type, such as strings, numbers, and tuples; the values ​​can be any Python data type.

1. Create a new Python dictionary

>>> dict1={} #建立一个空字典
Copy after login
>>> type(dict1)  < type &#39;dict&#39;>
Copy after login

2. Add Python dictionary elements: two methods

>>> dict1[&#39;a&#39;]=1 #第一种  
>>> dict1  
{&#39;a&#39;: 1}
Copy after login

#The second one: setdefault method

>>> dict1.setdefault(&#39;b&#39;,2)  
2  
>>> dict1  {&#39;a&#39;: 1, &#39;b&#39;: 2}
Copy after login

3 ,Delete Python dictionary

#删除指定键-值对  
>>> dict1  
{&#39;a&#39;: 1, &#39;b&#39;: 2}  
>>> del dict1[&#39;a&#39;] #也可以用pop方法,dict1.pop(&#39;a&#39;)  
>>> dict1  
{&#39;b&#39;: 2}  
#清空字典  
>>> dict1.clear()  
>>> dict1 #字典变为空了  
{}  
#删除字典对象  
>>> del dict1  
>>> dict1  Traceback (most recent call last):  
File "< interactive input>", line 1, in < module> 
NameError: name &#39;dict1&#39; is not defined
Copy after login

The above is the detailed content of Python dictionary adds a method to delete key values. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!