标签:font 重复 family lse 获取 使用 obb dict val
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
标签:font 重复 family lse 获取 使用 obb dict val
原文地址:https://www.cnblogs.com/cnhkzyy/p/9065919.html