Dictionary:
A python dictionary is another mutable container model, and can store any type of object, such as strings, numbers, tuples, and other container models.
First, create a dictionary
A dictionary consists of a pair of keys and corresponding values. Dictionaries are also referred to as associative arrays or hash tables. The basic syntax is as follows:
Dict = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}
You can also create a dictionary like this
Dict1 = {' abc ': 456}dict2 = {' abc ': 123, 98.6:37}
Attention:
Each key and value is separated by a colon (:), each pair is comma-delimited, each pair is separated by commas, and the whole is placed in curly braces ({}).
The key must be unique, but the value does not have to be.
The value can take any data type, but it must be immutable, such as a string, number, or tuple.
Second, access the values in the dictionary
Put the corresponding key into the familiar square brackets, the following example:
Dict = {'Name':'Zara',' Age': 7,'Class':' First'};Print "dict[' Name ']:", dict['Name'];Print "dict[' age ']:", dict[' Age'];#The result of the above example output:#dict[' Name ': Zara#dict[' age ': 7
If the data is accessed using a key that is not in the dictionary, the output error is as follows:
Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};p rint ' dict[' Alice ']: ", dict[' Alice ');
The result of the above example output:
#KeyError: ' Alice ' [/code]
Third, modify the dictionary
The way to add new content to a dictionary is to add a new key/value pair, modify or delete an existing key/value pair as follows:
Dict = {' Name ': ' Zara ', ' age ': 7, ' Class ': ' First '};d ict[' age ' = 8; # Update existing entrydict[' School '] = "DPS School"; # ADD new entry print "dict[' age '):", dict[' age '];p rint "dict[' School ']:", dict[' School '); #以上实例输出结果: #dict [' Age ']: 8#dict[' School ': DPS School
Iv. Deleting a dictionary element
The ability to delete a single element also clears the dictionary, emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:
Dict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First '};d el dict[' name ']; # Delete key is ' Name ' entry dict.clear (); # Empty dictionary all Entries del dict; # Delete the dictionary print "dict[' age ']:", dict[' age '];p rint "dict[' School ']:", dict[' School ']; #但这会引发一个异常 because the dictionary no longer exists after Del: dict[' age ' ]:
V. Characteristics of dictionary Keys
A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.
Two important points to keep in mind:
1) The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:
Dict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '};p rint ' dict[' name ']: ", dict[' name ']; #以上实例输出结果: #dict [' name ']: Manni
2) The key must be immutable, so it can be used as a number, string or tuple, so the list is not, the following example:
Dict = {[' name ']: ' Zara ', ' Age ': 7};p rint ' dict[' name ']: ", dict[' name ']; #以上实例输出结果: #TypeError: List objects is unhashable
Six, dictionary built-in functions & methods
The Python dictionary contains the following built-in functions:
CMP (Dict1, DICT2) #比较两个字典元素. Len (dict) #计算字典元素个数, which is the total number of keys. STR (dict) #输出字典可打印的字符串表示. Type (variable) #返回输入的变量类型 returns the dictionary type if the variable is a dictionary.
The Python dictionary contains the following built-in methods:
Radiansdict.clear () #删除字典内所有元素radiansdict. Copy () #返回一个字典的浅复制radiansdict. Fromkeys () #创建一个新字典, The key that is the dictionary of the elements in the sequence seq, Val is the initial value of the dictionary for all Keys Radiansdict.get (key, Default=none) #返回指定键的值, if the value does not return the default value in the dictionary Radiansdict.has _key (key) #如果键在字典dict里返回true, otherwise returns Falseradiansdict.items () #以列表返回可遍历的 (key, value) tuple array Radiansdict.keys () # Returns a dictionary with a list of all keys Radiansdict.setdefault (key, Default=none) #和get () similar, but if the key does not already exist in the dictionary, The key is added and the value is set to Defaultradiansdict.update (DICT2) #把字典dict2的键/value pair updated to Dict radiansdict.values () #以列表返回字典中的所有值
Seven, the Dictionary Practice code
Print ("' |---Welcome to the Address Book Program---| | ---1, contact information---| | ---2, insert a new contact---| | ---3. Delete an existing contact---| | ---4. Exit Address Book Program---| ") addressbook={} #定义通讯录while 1:temp=input (' Please enter Directive code: ') if not Temp.isdigit (): Print ("Input instruction error, follow prompt for") CO Ntinue Item=int (temp) #转换为数字 if Item==4:print ("|---Thanks for using the Address Book Program---|") Break name = input ("Please enter contact Name:") if item==1:if name in Addressbook:print (name, ': ', Addressbook[nam E]) Continue Else:print ("the contact does not exist!") ") if item==2:if name in Addressbook:print (" The name you entered already exists in the Address Book-->> ", Name,": ", Addressbook[name]) Isedit=input ("Whether to modify contact information (y/n):") if isedit== ' Y ': Userphone = input ("Please enter contact Phone:") Addressbook[name]=userphone Print ("Contact modified successfully") Continue else: Continue Else:userphone=input ("Please enter contact Phone:") Addressbook[name]=userphone print (" Join the success of the system! ") Continue if item==3:if name in Addressbook:del addressbook[name] Print ("Delete succeeded! ") Continue Else:print (" Contact does not exist ")
Python Basics-Dictionary