Adding and traversing Python dictionary key-value pairs
To add a key-value pair
First define an empty dictionary
dic={}
1
Assign a value directly to a key that does not exist in the dictionary to add
dic[' name ']= ' Zhangsan '
Dic
{' name ': ' Zhangsan '}
1
2
3
If key or value are variables, you can also use this method
Key= ' age '
Value=30
Dic[key]=value
Dic
{' Age ': +, ' name ': ' Zhangsan '}
1
2
3
4
5
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 ': ' ' name ': ' Zhangsan ', ' sex ': ' Male '}
1
2
3
4
5
6
7
8
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 is 001
Key is Age,value is 30
Key is Name,value are Zhangsan
Key is Sex,value are male
1
2
3
4
5
6
7
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 is 001
Key is Age,value is 30
Key is Name,value are Zhangsan
Key is Sex,value are male
1
2
3
4
5
6
7
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
Python Training Knowledge Summary Series-chapter II Python data Structure Part IV-Dictionary operations