python中的列表和字典
Posted cnhkzyy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python中的列表和字典相关的知识,希望对你有一定的参考价值。
三. 字典以及相关使用
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
以上是关于python中的列表和字典的主要内容,如果未能解决你的问题,请参考以下文章