Summary of the basic knowledge of the dictionary in Python, and summary of python
Define a dictionary
>>> d = {"server":"mpilgrim", "database":"master"} 1>>> d{'server': 'mpilgrim', 'database': 'master'}>>> d["server"] 2'mpilgrim'>>> d["database"] 3'master'>>> d["mpilgrim"] 4Traceback (innermost last):
File "<interactive input>", line 1, in ?
KeyError: mpilgrim
First, we create a new dictionary with two elements and assign it to variable d. Each element is a key-value pair, and the entire element set is enclosed in braces.
Server is a key word associated with mpilgrim, which is referenced by d ["server.
Database is a key word associated with a master, which is referenced by d ["database.
You can get the value through the key word, but not through the value to the key word. Therefore, d ["server"] Is mpilgrim, but using d ["mpilgrim"] causes an exception because mpilgrim is not a key word.
Modify a dictionary
>>> d{'server': 'mpilgrim', 'database': 'master'}>>> d["database"] = "pubs" 1>>> d{'server': 'mpilgrim', 'database': 'pubs'}>>> d["uid"] = "sa" 2>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}
Duplicate key words cannot exist in a dictionary. Assigning a value to an existing key word will erase the original value.
You can add new key-value pairs at any time. This syntax is the same as modifying existing values. (Yes, it may bring you trouble one day. You may think that you have added a new value, but in fact you have modified the same value repeatedly, because your key words have not changed as you think .)
Note that the new elements (uid and sa) appear in the middle of the dictionary. In fact, it is just a coincidence that the elements in the first example seem orderly. Now they seem unordered, which is even more a coincidence.
Note
The dictionary does not have the element order concept. It is incorrect to say that the order of elements is disordered. They are just unordered. This is an important feature that will harass you when you want to access dictionary elements in a specific, repeatable Order (like the alphabetic order of key words. There are some implementation methods that are not added to the dictionary.
Mix Data Types in dictionaries
>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'pubs'}>>> d["retrycount"] = 3 1>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}>>> d[42] = "douglas" 2>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 42: 'douglas', 'retrycount': 3}
The dictionary is not used only for strings. Dictionary values can be any data type, including strings, integers, objects, or even other dictionaries. In a single dictionary, the dictionary values do not need to be all of the same data type. You can mix and match the values as needed.
Dictionary keywords must be strict, but they can be strings, integers, and several other types (This will be discussed later ). You can also mix and match keywords in a dictionary.
Delete an element from a dictionary
>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 42: 'douglas', 'retrycount': 3}>>> del d[42] 1>>> d{'server': 'mpilgrim', 'uid': 'sa', 'database': 'master', 'retrycount': 3}>>> d.clear() 2>>> d{}
Del allows you to delete a single element from the dictionary based on the key.
Clear deletes all elements in a dictionary. Note that the set represented by empty braces indicates that a dictionary has no elements.
String is case sensitive
>>> d = {}>>> d["key"] = "value">>> d["key"] = "other value" 1>>> d{'key': 'other value'}>>> d["Key"] = "third value" 2>>> d{'Key': 'third value', 'key': 'other value'}
Assigning a value to an existing dictionary keyword simply replaces the old value with the new value.
In this case, a value is not assigned to an existing dictionary keyword. Because strings in Python are case sensitive, 'key' and 'key' are different. In this way, a new key/value pair is generated in the dictionary. It may be similar for you, but it is totally different for Python.
How to access the value in the dictionary:
>>> dict2 = {'name':'earth','port':80} >>> for key in dict2.keys(): ... print 'key=%s,value=%s' %(key,dict2[key])...key=name,value=earthkey=port,value=80>>> for key in dict2: ... print 'key=%s,value=%s' %(key,dict2[key])...key=name,value=earthkey=port,value=80
Obtain the value of an element in the dictionary:
>>> dict2['name']'earth'>>> print 'host %s is running on port %d' %(dict2['name'],dict2['port'])host earth is running on port 80
The method has_key () or in, not in to check whether a key exists in the dictionary.
>>> 'name' in dict2True>>> 'server' in dict2False>>> 'name' in dict2 True>>> dict2['name']'earth'>>> dict2.has_key('server')False>>> dict2.has_key('name') True
An example of mixing numbers and strings in a dictionary:
>>> dict3 = {}>>> dict3[1] = 'abc'>>> dict3['1'] = 3.14159>>> dict3[3.2] = 'xyz'>>> dict3{'1': 3.14159, 1: 'abc', 3.2: 'xyz'}
Overall assignment:
>>> dict3 = {'1': 3.14159, 1: 'abc', 3.2: 'xyz',33:'hehe'}>>> dict3{'1': 3.14159, 1: 'abc', 3.2: 'xyz', 33: 'hehe'}
Update dictionary:
>>> dict2['name'] = 'venus'>>> dict2['port'] = 6969>>> dict2['arch'] = 'sunos5'>>> print 'host %(name)s is running on port %(port)d' %dict2host venus is running on port 6969
Delete dictionary elements and dictionaries
>>> dict2{'arch': 'sunos5', 'name': 'venus', 'port': 6969}>>> del dict2['name']>>> dict2{'arch': 'sunos5', 'port': 6969}>>> dict2.clear()>>> dict2{}>>> del dict2>>> dict2Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'dict2' is not defined>>> dict3{'1': 3.14159, 1: 'abc', 3.2: 'xyz', 33: 'hehe'}>>> dict3.pop(33) 'hehe'>>> dict3{'1': 3.14159, 1: 'abc', 3.2: 'xyz'}
Note: avoid using the built-in object name as the variable identifier.
Similar to: dict, list, file, bool, str, input, len