【一】Python学习笔记---字典 -dictionary

1,认识Python中的字典

Python内置了字典:dict的支持,dict全称dictionary,

在其他语言中也称为map,

使用键-值(key-value)存储,具有极快的查找速度。

在Python中,字典是一系列键-值对,每个键都与一个值相关联。

可将任何Python对象,用作字典中的值。

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

这种key-value存储方式,在放进去的时候,必须根据key算出value的存放位置,这样,取的时候才能根据key直接拿到value。

key : value

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

2,添加 键-值对

字典是一种动态结构,可随时在其中添加键-值对(key :value)

要添加键值对,可依次指定字典名,用方括号括起的键和相关联的值

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

先创建一个空的字典,可先使用一对空的花括号定义一个字典,再分行添加各个键-值对

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

修改字典中的值

要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

删除 键值对

对于字典中不再需要的信息,可使用del 语句将相应的键-值对 彻底删除。

使用del 语句时,必须 指定字典名和要删除的键

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

del 语句删除的 键-值对 永久删除

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

由类似对象组成的字典

字典 存储一个对象的多种信息

存储众多对象的同一种信息

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

3,遍历字典

可遍历字典的所有键-值对 、键、值

遍历所有的 键- 值 对

for 循环遍历字典

要编写用于遍历字典的for循环,可声明两个变量 ,用于存储 键-值对中的键和值。

对于这两个变量,可使用任何名称

for k,v in user_0.items()

for 语句的第二部分包含,字典名和 方法items( )

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

遍历字典中的所有键

方法 keys( )

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

在这种循环中,可以使用当前键来访问与之相关联的值。

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

确定某个 是否在字典中

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

按顺序遍历字典中的所有键

要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。

可以使用函数 sorted( ) 来获得按特定顺序排列的键列表的副本:

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

按顺序遍历字典中的所有值

使用方法 values( )

返回一个值列表,而不包含任何键。

当值 有重复的时候 ,为剔除重复项,可使用 集合 set

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

《【一】Python学习笔记---字典 -dictionary》
《【一】Python学习笔记---字典 -dictionary》

    原文作者:聂红波
    原文地址: https://zhuanlan.zhihu.com/p/28198904
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞