【Python编程】字典及其使用

整理是为了方便自己学习记忆使用。

参考书籍《Python编程--从入门到实践》(第2版),[美] 埃里克·玛瑟斯。

一、使用字典

        字典是由键和值组成的,以成对的形式出现。

  键:值

child = { 'age' : 5,  'color' : 'red' }

        上述表达式,是字典的基本组成。其中age和color是键,5和red是值。键需要用单引号引起,当值为字符串的时候,也需要用单引号引起。

        键和值之间用冒号分割,而键值对之间用逗号分割。

1、访问字典中的值

        字典名[ '键' ]

child = {'age':5, 'color':'red'}
print(child['age'])
print(f"The child likes {child['color']}.")

2、添加键值对

        字典名[ '键名' ] = 值

child = {'age':5, 'color':'red'}
child['height'] = 150
child['fruits'] = 'apple'
print(child)

3、创建空字典

child = {}
child['height'] = 150
child['fruits'] = 'apple'
print(child)

4、修改字典中的值

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}
child['fruits'] = 'grape'
print(child)

5、删除键值对

        del  字典名[ '键名' ]

        用del删除键值对,删除的键值对会永远消失。

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}
del child['color']
print(child)

二、遍历字典

遍历所有键值对:for k,v in child.items()

遍历所有键:for k in child.keys()

遍历所有值:for k in child.values()

1、遍历所有键值对

        用for循环遍历整个字典。在这里k和v是两个变量,可以取任何名称。items() 返回一个键值对列表。

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}
for k,v in child.items():       # 这里是 字典名.items() 
    print(f"key:{k}")
    print(f"value:{v}\n")

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}
for k,v in child.items(): 
    print(f"{k.title()} is {v}.")

2、遍历字典中的所有键

   (1)遍历所有的键

        用for循环遍历所有的键,使用keys()会更清晰明了,但是也可以不用,得到的效果是一样的。

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}
for k in child.keys(): 
    print(f"{k.title()}")

   (2) 输出部分键的更多信息

        与列表建立联系。

        假设除了要遍历所有的键,你还想输出关于部分键更多的信息。那么建立一个列表,在for循环中插入if语句。在for循环中,假设你知道部分键的一些信息(if)。

3、按照特定顺序遍历所有的键

        采用字母顺序的方向,打印键名。

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}

for k in sorted(child.keys()): 
    print(f"{k.title()}")

4、遍历字典中所有的值

   (1)遍历所有的元素

child = {'age': 5, 'color': 'red', 'height': 150, 'fruits': 'apple'}

for v in child.values(): 
    print(f"{v}")

   (2)遍历所有不重复的元素

        下面的字典设立了两个重复值,用set()函数可以剔除重复值。

三、嵌套

1、字典列表

   (1)创建字典储存到空列表中

        字典child只保存了一个孩子的信息,但无法储存第二个孩子的信息,那么如何管理幼儿园所有的孩子信息呢?可以创建一个列表,每个child都是一个字典。

child1 = {'age': 5, 'color': 'red', 'height': 100, 'fruits': 'apple'}
child2 = {'age': 6, 'color': 'green', 'height': 110, 'fruits': 'grape'}
child3 = {'age': 7, 'color': 'purple', 'height': 120, 'fruits': 'banana'}

children = [child1, child2, child3]
for child in children:
    print(child)

   (2)批量创建字典放入空列表

children = []

# 创建三十个孩子的信息
for i in range(30):
    child = {'age': 5, 'height': 100, 'fruits': 'apple'}
    children.append(child)

# 展示前五个孩子的信息
for child in children[:5]:
    print(child)
print('...')

 2、在字典中储存列表

        在这里用到里递进的两个for循环,第一次循环是遍历键值对,取了n lg两个名称分别代表键和值。第二个递进for循环,是遍历每一个列表,取了la表示列表中的值,lg代表整个列表

languages = {'A':['Python', 'ruby'],
             'B':['C'],
             'C':['ruby', 'go']}
for n, lg in languages.items():
    print(f"\n{n.title()}'s favorite language are:")
    for la in lg:
        print(f"\t{la.title()}")

3、在字典中存储字典

        两个小的字典,可以分别看作是大字典中的键值对。 之后在小字典中利用 字典名[键名] 得到索引的值。

users = {'A':{'first': 'zhang',
              'last': 'yiyi',
              'location': 'beijing'},
         'B':{'first': 'wang',
              'last': 'erer',
              'location': 'tianjin'}}

for k, v in users.items():
    print(f"\n{k.title()}")
    
    name = f"{v['first']} {v['last']}"   # 在字符串中使用变量   v[]索引
    print(f"{name.title()}")
    
    location = v['location']
    print(f"{location.title()}")

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值