字典是一种可变容器模型,且可存储任意类型对象,是无序的
格式:dict_1 = {key1:value1,key2:value2,…}
key=value,key:value,这种格式的数据结构我们称之为映射(mapping)
映射指的是可以通过键(key)引用值(value),整体称之为键值对
字典是Python中唯一内建的映射类型
字典方法:
1.增加操作:
- 变量名[key] = value:通过key添加value值,如果key存在则覆盖
dict_1 = {"name":"张三","age":18} dict_1["name"] = "李四" print(dict_1) # {'name': '李四', 'age': 18} dict_1["gender"] = "男" print(dict_1) # {'name': '李四', 'age': 18, 'gender': '男'}
- setdefault(key,default_value):指定key和value(value默认为None),如果key存在则返回其值,不会修改原来的值,如果key不存在,则添加新的键值对
dict_1 = {"name":"张三","age":18} print(dict_1.setdefault("name")) # 张三 print(dict_1.setdefault("name","李四")) # 张三 print(dict_1) # {'name': '张三', 'age': 18} print(dict_1.setdefault("gender")) # None print(dict_1) # {'name': '张三', 'age': 18, 'gender': None}
注:该方法在添加新的键值对时是在原字典上操作的
2.删除操作:
- pop:弹出,返回并删除指定键对应的值
dict_1 = {"name":"张三","age":18} dict_1.pop("name") print(dict_1) # {'age': 18} dict_1.pop() print(dict_1) # TypeError: pop expected at least 1 arguments, got 0
- popitem:随机弹出一个键值元组,随机弹出是因为字典是无序的
dict_1 = {"name":"张三","age":18} print(dict_1.popitem()) # ('age', 18) print(dict_1) # {'name': '张三'}
- clear:清空字典
dict_1 = {"name":"张三","age":18} dict_1.clear() print(dict_1) # {}
- del:内置功能,删除整个字典或字典的数据
dict_1 = {"name":"张三","age":18} del dict_1["name"] print(dict_1) # {'age': 18} del dict_1 print(dict_1) # NameError: name 'dict_1' is not defined