三. 字典以及相關使用
1. 字典的定義 dict{}
2. 字典特征:字典是無序的,key-value鍵值對形式,key值不重復
3. 字典的賦值:dictA = {keyA: valueA, keyB: valueB, keyC: valueC}
4. 字典的取值:dictA[keyA] dictA.get(keyA)
5. 字典的所有鍵:dictA.keys() key-value獲取:dictA.items()
6. 修改字典中元素的值:dictA[keyA] = value
7. 獲取字典的長度:len(dictA)
8. 字典中添加元素:dictA[key_new] = value
9. 刪除字典所有元素:dictA.clear()
10. 刪除整個字典:del dictA
11. 字典組合:dict(dictA, **dictB) dictA.update(dictB)
四. 實例
1. 字典的定義,字典的鍵名只能是數字、字符串、元組,且不能重復
stu1 = {"name": "Mr.逗", "sex": "male", "age": 20, "hobby": "run"}
print(stu1)
結果:
{'sex': 'male', 'hobby': 'run', 'name': 'Mr.逗', 'age': 20}
2. 字典取值:dictA[keyA] dictA.get(keyA)
stu1 = {"name": "Mr.逗", "sex": "male", "age": 20, "hobby": "run"}
print(stu1["name"])
print(stu1.get("name"))
結果:
Mr.逗
Mr.逗
3. 修改字典值:dictA[keyA] = value,keyA是已存在的key
stu1 = {"name": "Mr.逗", "sex": "male", "age": 20, "hobby": "run"}
stu1["name"] = "Mr.小小逗"
print(stu1)
結果:
{'hobby': 'run', 'age': 20, 'name': 'Mr.小小逗', 'sex': 'male'}
4. 向字典中添加鍵值對,dictA[key_new] = value,key_new是不存在的
stu1 = {"name": "Mr.逗", "sex": "male", "age": 20, "hobby": "run"}
stu1["study"] = "python"
結果:
{'age': 20, 'study': 'python', 'name': 'Mr.逗', 'sex': 'male', 'hobby': 'run'}
5. 獲取字典的長度:len(dictA)
stu1 = {"name": "Mr.逗", "sex": "male", "age": 20, "hobby": "run"}
print(len(stu1))
結果:
4
6. 兩個字典的組合:dictA.update(dictB) dict(dictA, **dictB)
B = {"name": "xiaojian", "age": 28, "is_marry": False}
B.update({"role": "teacher", "class": "python"})
print(B)
結果:
{'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)
結果:
{'class': 'python', 'is_marry': False, 'age': 28, 'role': 'teacher', 'name': 'xiaojian'}
7. 刪除字典中所有元素:dictA.clear(),只是清空字典
a = {"name": "Jack", "sex": "M"}
a.clear()
print(a)
結果:
{}
8. 刪除整個字典:del dictA
a = {"name": "Jack", "sex": "M"}
del a
print(a)
結果:
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
print(a)
NameError: name 'a' is not defined
