The following small series will bring you a python dictionary key-value pair addition and traversal method. I think this is quite good. now I will share it with you and give you a reference. Let's take a look at it with Xiaobian.
Add a key-value pair
First define an empty Dictionary
>>> Dic = {}
Directly assign values to keys that do not exist in the dictionary.
>>> dic['name']='zhangsan'>>> dic{'name': 'zhangsan'}
This method can also be used if both the key and value are variables.
>>> key='age'>>> value=30>>> dic[key]=value>>> dic{'age': 30, 'name': 'zhangsan'}
Here we can see that the data in the dictionary is not arranged in order. if you are interested, you can search for the hash table in the data structure.
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'}
Traverse Dictionary
There are two methods
Method 1:Obtain the key first, and then obtain the value through dic [key ].
>>> for key in dic:... print 'key is %s,value is %s'%(key,dic[key])...key is id,value is 001key is age,value is 30key is name,value is zhangsankey is sex,value is male
Method 2:Sequentially unpackage the list of tuples returned by the items () method.
>>> for key,value in dic.items():... print 'key is %s,value is %s'%(key,value)...key is id,value is 001key is age,value is 30key is name,value is zhangsankey is sex,value is male
If you are not familiar with list, tuples, and sequence unpacking, you 'd better understand them in depth. It can be understood in combination with arrays, List classes, and hash tables in your familiar C # or JAVA language.
The method for adding and traversing the above python dictionary key-value pairs is all the content that I have shared with you. I hope to give you a reference and support for PHP.
For more articles about how to add and traverse a python dictionary key-value pair, refer to PHP!