The properties of the dictionary key:
(1) The same key is not allowed to appear two times: when created, if the same key is assigned two times, the latter value overrides the previous
(2) The key must be immutable, so it can be used as a number, a string, or a tuple, but not with a list.
format:d = {key1:value1, key2:value2}
Dictionary creation:
#元组列表形式创建字典:
>>> Dic1 = dict ([' IP ', ' 127.0.0.1 '],[' port ', ' 8080 '])
>>> Dic1
{' IP ': ' 127.0.0.1 ', ' Port ': ' 8080 '}
#列表元组形式创建字典:
>>> dic2 = dict ([' IP ', ' 192.168.1.1 '), (' Port ', ' 443 ')])
>>> Dic2
{' IP ': ' 192.168.1.1 ', ' Port ': ' 443 '}
#表达式方式创建字典: Note If a string cannot be created in this way!
>>> dic3 = dict (x=10,y=20,z=30)
>>> DIC3
{' Z ': +, ' x ': ten, ' Y ': 20}
#**dic3 way to create a dictionary
>>> dic4 = dict (**DIC3)
>>> Dic4
{' Z ': +, ' x ': ten, ' Y ': 20}
#fromkeys方式创建字典: Creates a default dictionary in which elements in the dictionary have the same value values
>>> dic5 = {}.fromkeys (' x ', ' y '), 100)
>>> DIC5
{' x ': +, ' y ': 100}
>>> dic6 = {}.fromkeys (' x ', ' Y ')
>>> dic6
{' x ': ' Y '}
>>> Dic7 = {}.fromkeys ([' X ', ' Y '])
>>> Dic7
{' X ': None, ' Y ': none}
>>> Dic8 = {}.fromkeys (' abcd ', ' 1 ')
>>> Dic8
{' B ': ' 1 ', ' C ': ' 1 ', ' A ': ' 1 ', ' d ': ' 1 '}
Dictionary access:
Dict1 = {'Name':'Runoob',' Age': 7,'Class':' First'} Print("dict[' Name ']:", dict['Name'])Print("dict[' age ']:", dict[' Age'])
Output Result:
dict1['Name': runoobdict1['age': 7
Dictionary traversal:
>>> dict = {'IP':'127.0.0.1','Port ' ': Z} for in dict: print(' dict[%s]=%s ' % (I,dict[i]))
Output Result:
dict[port]=80Dict[ip]=127.0.0.1
To modify a dictionary:
Dict1 = {'Name':'Runoob',' Age': 7,'Class':' First'}dict1[' Age'] = 8;#Update Agedict1['School'] ="Beginner's Tutorial" #Add new informationPrint("dict[' age ']:", dict[' Age'])Print("dict[' School ']:", dict['School'])
Output Result:
dict1['age ': 8dict1['School']: Beginner's Tutorial
Dictionary Delete:
>>> Dict1 = {'Name':'Runoob',' Age': 7,'Class':' First'}>>> Dict1.pop (' Age')#Delete a key value>>>dict1{'Class':' First','Name':'Runoob'}>>>deldict1['Name']#Delete a key value>>>dict1{'Class':' First'}>>> Dict1.clear ()#Empty Dictionary>>>dict1{}>>>delDict1#Delete entire dictionary>>>delDict1>>>Dict1traceback (most recent): File"<pyshell#96>", Line 1,inch<module>Dict1nameerror:name'Dict1' is notDefined
Dictionary built-in functions:
Len (dict)#Computes the number of dictionary elements, that is, the total number of keysSTR (DICT)#The output dictionary is represented as a printable string>>> dict = {'Name':'Runoob',' Age': 7,'Class':' First'}>>>Str (dict)"{' Name ': ' Runoob ', ' Class ': ' First ', ' Age ': 7}". Clear ()#Delete all elements in a dictionary. Copy ()#returns a shallow copy of a dictionary. Fromkeys ()#Create a new dictionary with the keys to the dictionary in sequence seq, Val is the initial value corresponding to all keys in the dictionary. Get (Key,default=none)#returns the value of the specified key if the value does not return the default value in the dictionary. Items ()#returns an array of traversed (key, value) tuples as a list. Keys ()#returns a dictionary of all keys in a list>>> D1 = {'Addr':{'IP': 127.0.0.1,'Port': 80},'msg': 18}>>>D1.keys () Dict_keys (['msg','Addr']). VALUES ()#returns all values in the dictionary as a list>>> D1 = {'Addr':{'IP': 127.0.0.1,'Port': 80},'msg': 18}>>>d1.values () dict_values ([19, {'IP':'127.0.0.1','Port': 80}]). SetDefault (key, default=none)#similar to get (), but if the key does not exist in the dictionary, the key is added and the value is set to default. Update (DICT2)#update the key/value pairs of the dictionary dict2 to the Dict>>> D1 = {'Addr':{'IP': 127.0.0.1,'Port': 80},'msg': 18}>>> D1.update ({'msg': 19})>>>d1{'msg': 19,'Addr': {'IP':'127.0.0.1','Port': 80}}
Example:>>> questions = ['name','Quest','Favorite Color']>>> answers = ['Lancelot','The Holy Grail','Blue']>>> forQ, ainchZip (questions, answers): ...Print('What is your%s? It is%s.'%(q, a))#print (' questions[%s] = answers[%s] '% (q,a))output Result: what isYour name? It isLancelot. what isYour quest? It isThe Holy Grail. what isYour favorite color? It isBlue.#Questions[name] = Answers[lancelot]#Questions[quest] = answers[the Holy Grail]#Questions[favorite color] = Answers[blue]
Example: for in Reversed (range (1, 2)): print(i) Output:97531
>>> l1=[1,2,3 > >> l2=[ a ", " b ", " c ]dict (Map ( lambda X,y:[x,y], L1,L2)) Output: { 1: " a ' , 2: " b , 3: " c }
Python: Dictionary