目录索引
- ==字典的意义和特征:==
- ==创建字典的语法:==
创建空字典的两种形式:
创建字典的形式:
- *直接用大括号包裹即可:*
- ==字典的常见操作:==
新增及修改:
删除:
- ***语法:***
- *clear()清空字典:*
查询:
- *key值查找:*
- *get()语法:*
- *keys():*
- *values():*
- *items():*
- ==字典的遍历循环:==
遍历字典的key:
遍历字典的value:
遍历字典的项:
遍历字典的键值对:
if i in dic语法:
字典的意义和特征:
- 字典里面的数据是以键值对的形式出现,和数据顺序无关,可以避免顺序出错从而查找不到数据
- 字典不支持下标
- 符号为大括号
- 各个键值对之间用逗号隔开
- 冒号前面的称为键(key),冒号后面的称为值(value)
- 不可变类型才能作为键,但值就无所谓了
创建字典的语法:
创建空字典的两种形式:
1.直接使用大括号:
dic = {}
2.采用语法:
dic = dict()
创建字典的形式:
直接用大括号包裹即可:
dic = {"TOM":18,"Jack":19}
字典的常见操作:
字典为可变数据类型
新增及修改:
语法:
字典序列名[key]=值
有则增,无则改:如果key存在则修改这个key对应的值,如果key不存在则新增此键值对
#举个例子:
dic = {"TOM":18,"Jack":19}
dic["Rose"] = 22
print(dic)
dic["TOM"] = 50
print(dic)
呈现效果:
删除:
语法:
del()或del:删除字典或删除字典中指定的键值对
#举个例子:
dic = {"TOM":18,"Jack":19}
# del(dic)或下方那个也可以
del dic
print(dic)
clear()清空字典:
dic = {"TOM":18,"Jack":19}
dic.clear()
print(dic)
呈现效果:
查询:
key值查找:
dic = {"TOM":18,"Jack":19}
print(dic["TOM"]) #18
print(dic["XIAO"]) #报错
呈现效果:
如果当前查找的key存在,则返回对应的值,否则就报错
get()语法:
字典序列名.get(key,默认值)
如果当前查找的key不存在则返回第二个参数,如果省略第二个参数,则返回None
#举个例子:
dic = {"TOM":18,"Jack":19}
print(dic.get("TOM"))#存在就正常返回
print(dic.get("XIAO",99)) #不存在,返回99
print(dic.get("XIAO")) #None
呈现效果:
keys():
用于取出所有键名
dic = {"TOM":18,"Jack":19}
dic_keys = dic.keys()
print(type(dic_keys))
print(dic_keys)
for i in dic_keys:#可以直接遍历
print(i)
呈现效果:
values():
用于取出所有值
dic = {"TOM":18,"Jack":19}
dic_values = dic.values()
print(type(dic_values))
print(dic_values)
for i in dic_values:
print(i)
呈现效果:
items():
把键值对整个成元组,排列出来
#举个例子:
dic = {"TOM":18,"Jack":19}
dic_items = dic.items()
print(type(dic_items))
print(dic_items)
for i in dic_items:
print(i)
呈现效果:
字典的遍历循环:
遍历字典的key:
dic = {"TOM":18,"Jack":19}
for i in dic.keys():
print(i)
呈现效果:
遍历字典的value:
dic = {"TOM":18,"Jack":19}
for i in dic.values():
print(i)
呈现效果:
遍历字典的项:
dic = {"TOM":18,"Jack":19}
for i in dic.items():
print(i)
呈现效果:
遍历字典的键值对:
dic = {"TOM":18,"Jack":19}
for key,value in dic.items():#拆包
print(key,"------>>",value)
呈现效果:
if i in dic语法:
该语法是用来判断元素是否在序列中,在字典里,这个语法用来判断的是字典的键是否存在,与值无关
dic = {"TOM":18,"Jack":19}
if "TOM" in dic:
print("键存在")
if 18 in dic:
print("值存在")
#运行结果:键存在