Add a key value pair
Define an empty dictionary first
>>> dic={}
To add a key that does not exist in the dictionary directly.
>>> dic[' name ']= ' Zhangsan '
>>> dic
{' name ': ' Zhangsan '}
If key or value are variables, you can use this method
>>> key= ' age '
>>> value=30
>>> dic[key]=value
>>> dic
{' Age ': ' Name ': ' Zhangsan '}
Here you can see the data in the dictionary is not in order, if interested, you can search the data structure of--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 ': ' Name ': ' Zhangsan ', ' sex ': ' Male '}
Traverse Dictionary
There are two ways of doing this.
Method 1: get the key first, then get value via Dic[key]
>>> for key in dic:
... print ' key is%s,value '%s '% (Key,dic[key])
...
The key is Id,value is 001 The key is Age,value is-is-
Name,value is Zhangsan The key 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) ...
The key is Id,value is 001 The key is Age,value is-is-
Name,value is Zhangsan The key is Sex,value is
male
If you are unfamiliar with lists, tuples, and sequences, it is best to have a look at Baidu and understand them in depth. Can be understood in conjunction with arrays, list classes, and hash tables in your familiar C # or Java language
The above Python dictionary key value pairs of add and traverse method is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.