Python dictionary key-Value Pair addition and traversal methods, python dictionary
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 the help house.