Home>Article>Backend Development> Python dictionary adds a method to delete key values

Python dictionary adds a method to delete key values

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼 Original
2019-06-15 17:20:47 7943browse

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={} #建立一个空字典
>>> type(dict1) < type 'dict'>

2. Add Python dictionary elements: two methods

>>> dict1['a']=1 #第一种 >>> dict1 {'a': 1}

#The second one: setdefault method

>>> dict1.setdefault('b',2) 2 >>> dict1 {'a': 1, 'b': 2}

3 ,Delete Python dictionary

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

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!

Statement:
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