to add a key-value pair
First define an empty dictionary
>>> dic={}
Assign a value directly to a key that does not exist in the dictionary to add
>>> dic[' name ']= ' Zhangsan ' >>> dic{' name ': ' Zhangsan '}
If key or value are variables, you can also use this method
>>> key= ' age ' >>> value=30>>> dic[key]=value>>> dic{' age ': ' Name ': ' Zhangsan '}
Here you can see that the data in the dictionary is not in chronological order, if interested, you can search the data structure--hash table
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 ': ' The ' name ': ' Zhangsan ', ' sex ': ' Male '}
Traverse Dictionary
There are two ways of doing this.
Method 1: get the key first and then get the value by Dic[key]
>>> for key in dic: ... print ' key is%s,value '%s '% (Key,dic[key]) ... key is Id,value are 001key is Age,value are 30key is Name,value Y is Sex,value is male
Method 2: sequence unpack the list of tuples returned by the dictionary items () method
>>> for Key,value in Dic.items (): ... print ' key is%s,value%s '% (key,value) ... key is Id,value are 001key is Age,value are 30key is name,value it zhangsankey I S Sex,value is male
If you are unfamiliar with lists, tuples, and sequence unpacking, it is best to get a better understanding of them by Baidu. Can be understood in combination with arrays, list classes, and hash tables in your familiar C # or Java language
Above this Python dictionary key value pair's addition and the traversal method is the small part to share to everybody's whole content, hoped can give everybody a reference, also hoped that everybody many support topic.alibabacloud.com.