字典的意义和特征:
- 字典里面的数据是以键值对的形式出现,和数据顺序无关,可以避免顺序出错从而查找不到数据
- 字典不支持下标
- 符号为大括号
- 各个键值对之间用逗号隔开
- 冒号前面的称为键(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)
呈现效果:
文章来源:https://www.toymoban.com/news/detail-453144.html
if i in dic语法:
该语法是用来判断元素是否在序列中,在字典里,这个语法用来判断的是字典的键是否存在,与值无关文章来源地址https://www.toymoban.com/news/detail-453144.html
dic = {"TOM":18,"Jack":19}
if "TOM" in dic:
print("键存在")
if 18 in dic:
print("值存在")
#运行结果:键存在
到了这里,关于【字典详细介绍】——python基础——如桃花来的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!