六、字 典

1. 简介

  • 一系列键-值对
  • 可将任何Python对象用作字典中的值
# 健值之间冒号分隔,健值对之间逗号分隔
# 键重复无语法错误,以最后一组为准
alien_0 = {'color': 'green', 'points': 5}

# 访问字典中的值
print(alien_0['color'])	

2. 使用字典

(1) 添加键-值对

	alien_0['x_position'] = 0
	alien_0['y_position'] = 25
	print(alien_0)

=>

# 健-值对的排列顺序与添加顺序不同
{'color': 'green', 'points': 5, 'y_position': 25, 'x_position': 0}

(2) 修改字典中的值

alien_0['color'] = 'yellow'
print('The alien is now ' + alien_0['color']  + ".")

=>

The alien is now yellow.

(3) 删除键-值对

del alien_0['points']
print(alien_0)

=>

{'color': 'yellow', 'y_position': 25, 'x_position': 0}

(4) 多行定义字典的格式

# 1. 左花括号后按回车
favorite_languages = {
# 2. 下面各行缩进四个空格,指定一组健-值对,后面加逗号
    ‘jen’: 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
# 3. 最后一组健-值对的下一行缩进四个空格并添加一个右花括号
    }

(5) 将较长的print语句分成多行

# 1. 输出的第一部分紧跟在左括号后面,末尾加一个拼接运算符(+)
print("Sarah's favorite language is " + 
# 2. 回车进入print语句的后续各行,用Tab键将它们对齐并缩进一级
    favorite_languages['sarah'].title() + 
# 3. 末行末尾加右括号
    ".")

3. 遍历字典

(1) 遍历所有的键-值对

items() 返回一个健-值对列表

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
    }
    
# 键和值可使用任何名称
for key, value in user_0.items():
    print("\nkey: " + key)
    print("value: " + value)
    
=>

# 遍历字典时,键-值对的返回顺序也与存储顺序不同

key: last
value: fermi

key: first
value: enrico

key: username
value: efermi

(2) 遍历所有键

keys() 返回一个包含字典中所有键的列表

favorite_languages = {
    ‘jen’: 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
    
# keys() 返回一个包含字典中所有键的列表
# if 'erin' not in favorite_languages.keys():
#     print("Erin, please take our poll!") => Erin, please take our poll!

# 遍历字典时默认遍历所有的键,所以这行等价于“for name in favorite_languages:”
for name in favorite_languages.keys():
    print(name.title())
    
=>

Jen
Sarah
Phil
Edward

按顺序遍历

在for循环中对返回对键进行排序

for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")
    
=>

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

(3) 遍历所有值

values() 返回一个值列表

for language in favorite_languages.values():
    print(language.title())
    
=>

Python
C
Python
Ruby

集合set剔除重复项

for language in set(favorite_languages.values()):
    print(language.title())
    
=>

Python
C
Ruby

4. 嵌套

(1) 字典列表

alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
aliens = [alien_0, alien_1]
aliens.append({'color': 'red', 'points': 15})

for alien in aliens:
    print(alien)
    
=>

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

(2) 在字典中存储列表

将一个键关联到多个值

  • 注意:列表和字典的嵌套层级不应太多
pizza = {
    'crust': 'thick',
    'toppings:' ['mushrooms', 'extra cheese'],
    }
    
for topping in pizza['toppings']:
    print(topping)
    
=>

mushrooms
extra cheese

(3) 在字典中存储字典

表示各用户的字典结构都相同,可使嵌套字典处理起来更容易

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },
    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },
    }
    
for username, user_info in users.items():
    print("\nUsername: " + username)
    full_name = user_info['first'] + " " + user_info['last']
    location = user_info['location']
    print("\tFull name: " + full_name.title())
    print("\tLocation: " + location.title())
    
=>

Username: aeinstein
    Full name: Albert Einstein
    Location: Princeton
    
Username: mcurie
    Full name: Marie Curie
    Location: Paris
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值