字典是用键值对的方式进行数据进新存储
字典的表现方式:
dict = {"key1"="value1","key2”="value2","key3"="value3"}
name = ["我","吴彦祖","彭于晏"]
characteristic = {"帅","很帅","非常帅"}
dicty = dict(zip(name,characteristic))
print(dicty)
打印出来的结果为:
![](https://i-blog.csdnimg.cn/blog_migrate/5cf5ea7c942062bca666eaaaece5ca71.png)
若对字典进行增加,修改和删除,可进行以下的操作:
增加:
name = ["我","吴彦祖","彭于晏"]
characteristic = {"帅","很帅","非常帅"}
dicty = dict(zip(name,characteristic))
print(dicty)
dicty["朱垲"] = "小丑"
print(dicty)
可以直接进行添加。
修改:
name = ["我","吴彦祖","彭于晏"]
characteristic = {"帅","很帅","非常帅"}
dicty = dict(zip(name,characteristic))
print(dicty)
dicty["朱垲"] = "小丑"
print(dicty)
dicty["我"] = "超级大帅哥"
print(dicty)
与增加一样,可直接进行修改。
![](https://i-blog.csdnimg.cn/blog_migrate/6369a66d7ca2459e3e9c9d842bc398c6.png)
删除:
对于字典中不需要的信息,可使用del语句将对应的键值对彻底删去。使用del语句时,必须指定字典名和要删除的键。
name = ["我","吴彦祖","彭于晏"]
characteristic = {"帅","很帅","非常帅"}
dicty = dict(zip(name,characteristic))
print(dicty)
dicty["朱垲"] = "小丑"
print(dicty)
dicty["我"] = "超级大帅哥"
print(dicty)
del dicty["吴彦祖"]
print(dicty)
可得到一下结果:
![](https://i-blog.csdnimg.cn/blog_migrate/934ec5e804788057be9e223b4695898a.png)
查找:
使用get()来查找值,如果查找的值不存在的话则会反生报错。
name = ["我","吴彦祖","彭于晏"]
characteristic = {"帅","很帅","非常帅"}
dicty = dict(zip(name,characteristic))
print(dicty)
new_ = dicty.get("吴彦祖")
print(new_)
![](https://i-blog.csdnimg.cn/blog_migrate/3ad0b452183b20ebc0bc85c281838d2c.png)
则会输出需要查找的值。
遍历:
可以通过items()来获取键值对的远足。
dictionary = {"我":"男","小明":"男","小红":"女"}
for item in dictionary.items():
print(item)
如果想获得具体的值,可进行以下操作:
dictionary = {"我":"男","小明":"男","小红":"女"}
for item,sex in dictionary.items():
print(f"{item}的性别是{sex}")