How to add and delete key values in python dictionary?
Related recommendations: "python Video"
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!