Add key-value pairs
##First define an empty dictionary (recommended Learn: Python video tutorial)
>>> dic={}
Directly assign a value to a key that does not exist in the dictionary to add
>>> dic['name']='zhangsan' >>> dic {'name': 'zhangsan'}
If the key or This method can also be used if value is a variable
>>> key='age' >>> value=30 >>> dic[key]=value >>> dic {'age': 30, 'name': 'zhangsan'}
You can also use the setdefault method of the dictionary
>>> dic.setdefault('sex','male') 'male' >>> key='id' >>> value='001' >>> dic.setdefault(key,value) '001' >>> dic {'id': '001', 'age': 30, 'name': 'zhangsan', 'sex': 'male'}
The above is the detailed content of How to add key-value pairs in python dictionary. For more information, please follow other related articles on the PHP Chinese website!