python基础之字典以及增删改查

字典:字典是python中唯一的一个映射类型,主要形式为 dic = {key1:value,key2:value2,....}
   字典中key的值是唯一的,主要关系到HASH算法,并且key的值必须是不可变的数据类型,values没有要求,可以放任何东西。

1.增
dic = {}
dic["abc"] = ("hehe")
dic["abc"] = ("123")
dic.setdefault("abc","123")
print(dic)

2.删
dic = {"入手必备":"塞尔达传说","高分巨作":"马里奥奥德赛","高分经典":"马里奥赛车","动作大片":"异度之刃"}
del dic["高分巨作"]
dic.pop("入手必备")
dic.popitem()
dic.clear()
print(dic)

3.改
dic = {"入手必备":"塞尔达传说","高分巨作":"马里奥奥德赛","高分经典":"马里奥赛车","动作大片":"异度之刃"}
dic1 = {"家庭必备":"分手厨房","高分巨作":"炸弹人"}
dic["入手必备"] = "碧姬公主"
dic.update(dic1)
print(dic)

4.查
dic = {"入手必备":"塞尔达传说","高分巨作":"马里奥奥德赛","高分经典":"马里奥赛车","动作大片":"异度之刃"}
print(dic["高分巨作"]) #key找不到会报错
print(dic.get("高分巨作")) #
print(dic.get("hehe","hahaha")) # 如果key找不到,返回第二个值,没有第二个值,返回NONE,不会报错


5.其他操作:
dic = {"入手必备":"塞尔达传说","高分巨作":"马里奥奥德赛","高分经典":"马里奥赛车","动作大片":"异度之刃"}
print(dic.keys()) #输出一个类列表,但不是列表!!!,不过可以当作列表来使用
print(dic.values())
for el in dic:
print(el)
print(dic.items()) #生成一个类元祖

tips:重要,用FOR循环得到keys和values
for el in dic.items():
print(type(el),el)
print(type(el[0]), el[0])
print(type(el[1]), el[1])
for k,v in dic.items():
print(k,v)
posted @ 2018-10-23 16:29  Mixtea  阅读(199)  评论(0编辑  收藏  举报