"""
字典
why:
列表的缺点:
1.列表如果存储的数据比较多,那么他的查询速度相对慢.
2.列表存储的数据关联性不强
what:python基础数据类型之一:字典
python中唯一的映射类的数据.是以键值对形式存储,{}表示.
每一对键值对以逗号隔开的.
{"name": "太白金星", "age": 18, "sex": "man"}
ps:
数据类型的划分:
容器型数据类型:list, tuple, dict, set
非容器型数据类型:int, str, bool
可变(不可hash)的数据类型:list, dict set
不可变(可hash)的数据类型:int, str, bool, tuple
字典是以键值对形式存储的,
键(Key): 不重复的,唯一的,键的数据类型必须是不可变的数据类型
值: 任意数据类型
字典可以存储大量的键值对数据
python3.5包括3.5之前:字典是无序的
python3.6之后:字典是有序的
字典的优点:
1. 字典存储大量的关系型数据
2. 字典的查询速度非常快
how
where
"""
# 不能存储重复的键值对
# dic = {
# "name": "alex",
# "name": "太白金星",
# "age": 18
# }
# print(dic)
# dic = {
# "name_list": ["博哥", "菊哥", "b哥"],
# "barry": {
# "name": '太白金星',
# "age": 18,
# "hobby": "wife"
# }
# }
# print(dic)
# 增删改查
# dic = {
# "name": '太白金星',
# "age": 18,
# "hobby": "wife"
# }
# 增
# 1.有则修改,无则添加
# dic["hight"] = 176
# print(dic)
# dic["age"] = 23
# print(dic)
# 2.有则不变,无则添加
# dic.setdefault("weight") # {'name': '太白金星', 'age': 18, 'hobby': 'wife', 'weight': None}
# dic.setdefault("weight", 160) # {'name': '太白金星', 'age': 18, 'hobby': 'wife', 'weight': 160}
# dic.setdefault("name", "barry") # {'name': '太白金星', 'age': 18, 'hobby': 'wife'}
# print(dic)
# 删
# pop 按照键删除
# dic.pop("age") # 按照键删除掉键值对
# dic.pop("age1") # 没有会报错
# dic.pop("age1", None) # 设置两个参数,第二个参数是提示语,一般设置成None
# print(dic)
# clear 清空
# dic.clear()
# print(dic)
# popitem(随机删除) 3.6版本之后就是删除最后一个键值对
# ret = dic.popitem()
# print(ret)
# print(dic)
# del
# del dic["name"] # 按照键删除,无此键会报错
# del dic # 删除字典
# print(dic)
# 改
# dic["age"] = 30
# print(dic)
# update
# dic.update(car="逍客", money=1300)
# dic = {"name": "jin", "age": "18", "sex": "male"}
# dic2 = {"name": "alex", "weight": 75}
# dic2.update(dic)
# # 将dic里面的键值对覆盖添加到dic2中
# print(dic)
# print(dic2)
# print(dic)
# 查
# 1.
# print(dic["age"]) # 按照键去查
# print(dic["age1"]) # 没有会报错
# 2.
# print(dic.get("age"))
# print(dic.get("age1")) # 没有键默认返回None
# print(dic.get("age1", "没有此键")) # 可以设置返回值
# dic.keys() 类似于list容器类类型
# ret = dic.keys()
# print(ret, type(ret)) # dict_keys(['name', 'age', 'hobby']) <class 'dict_keys'>
# for key in ret:
# print(key)
# 可以转化成list
# print(list(ret))
#
# print(dic.values())
# print(list(dic.values())) # 转化成list
# for v in dic.values():
# print(v)
#
# print(dic.items())
# print(list(dic.items()))
# for i in dic.items():
# print(i)
# 分别赋值
# a, b = (1, 2)
# print(a, b)
# a, b = 100, 1000
# print(a, b)
# a, b = [100, 1000]
# print(a, b)
# a, b = {"name": "alex", "age": 73}
# print(a, b)
# 面试题:
"""
a = 18
b = 32
通过一行代码将a, b的值互换
"""
# a = 18
# b = 32
# a, b = b, a
# print(a, b)
# dic = {
# "name": '太白金星',
# "age": 18,
# "hobby": "wife"
# }
# for k, v in dic.items():
# print("这是一个键:", k)
# print("这是一个值:", v)
#