three. Dictionaries and related uses
1. Dictionary definition dict{}
2. Dictionary features: Dictionary is unordered, key-value key value pair form, key value is not duplicated
3. Assignment of dictionaries: dicta = {Keya:valuea, Keyb:valueb, KEYC:VALUEC}
4. Dictionary value: Dicta[keya] Dicta.get (Keya)
5. All keys of the Dictionary: Dicta.keys () Key-value get: Dicta.items ()
6. Modify the value of the element in the dictionary: Dicta[keya] = value
7. Get the length of the Dictionary: Len (dicta)
8. Adding elements to the dictionary: dicta[key_new] = value
9. Delete all elements of the Dictionary: Dicta.clear ()
10. Delete the entire dictionary: del dicta
11. Dictionary combination: Dict (dicta, **DICTB) dicta.update (DICTB)
Four. Example
1. Dictionary definition, the dictionary key name can only be a number, a string, a tuple, and can not be repeated
STU1 = {"name":"Mr. Tease","Sex":"male"," Age": 20,"Hobby":"Run"}Print(STU1) Result: {'Sex':'male','Hobby':'Run','name':'Mr. Tease',' Age': 20}
2. Dictionary value: Dicta[keya] Dicta.get (Keya)
STU1 = {"name":"Mr. Tease","Sex":"male"," Age": 20,"Hobby":"Run"}Print(stu1["name"])Print(Stu1.get ("name") Results: Mr. Tease Mr. Tease
3. Modify Dictionary value: Dicta[keya] = Value,keya is already existing key
STU1 = {"name":"Mr. Tease","Sex":"male"," Age": 20,"Hobby":"Run"}stu1["name"] ="Mr. Little Tease"Print(STU1) Result: {'Hobby':'Run',' Age': 20,'name':'Mr. Little Tease','Sex':'male'}
4. Add a key-value pair to the dictionary, dicta[key_new] = Value,key_new is not present
STU1 = {"name":"Mr. Tease","Sex":"male"," Age": 20,"Hobby":"Run"}stu1["study"] ="python"Result: {' Age': 20,'study':'python','name':'Mr. Tease','Sex':'male','Hobby':'Run'}
5. Get the length of the Dictionary: Len (dicta)
stu1 = { " name ": " mr. Tease ", " sex ": " male ", " age : " Hobby ": " Run } Print (Len (STU1)) Results: 4
6. A combination of two dictionaries: Dicta.update (DICTB) dict (dicta, **DICTB)
B = {"name":"Xiaojian"," Age": 28,"Is_marry": False} B.update ({"role":"Teacher","class":"python"})Print(B) Result: {'class':'python','Is_marry': False,' Age': 28,'role':'Teacher','name':'Xiaojian'}
B = {"name":"Xiaojian"," Age": 28,"Is_marry": False} C= {"role":"Teacher","class":"python"}d= Dict (B, * *C)Print(D) Result: {'class':'python','Is_marry': False,' Age': 28,'role':'Teacher','name':'Xiaojian'}
7. Delete all the elements in the Dictionary: Dicta.clear (), just empty the dictionary
A = {"name""Jack""sex"" M"}a.clear ()print(a) result: {}
8. Delete the entire dictionary: del dicta
A = {"name":"Jack","Sex":"M"}delaPrint(a) Result: Traceback (most recent): File"<pyshell#5>", Line 1,inch<module>Print(a) Nameerror:name'a' is notDefined
Lists and dictionaries in Python (ii)