Python笔记4---字典

六、字典

 6.1 一个简单的字典

 

在Python中,字典用放在花括号{} 中的一系列键_值对表示。
alien_0 = {'color': 'green', 'points': 5}

print(alien_0['color'])
print(alien_0['points'])

代码输出:

    green
  5

  6.2 使用字典 

  在Python中,字典是一系列键_值对每个 都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。

  alien_0 = {'color': 'green', 'points': 5}

   6.2.1 访问字典里的值

 

要获取与键相关联的值,可依次指定字典名放在方括号内的键。
alien_0 = {'color': 'green', 'points': 5}

new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")

6.2.2 添加键_值对
字典是一种动态结构,要添加键_值对,可依次指定字典名、用方括号括起的键和相关联的值
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

代码输出:

   {'color': 'green', 'points': 5}
   {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

   6.2.3 先创建一个空字典

  在空字典中添加键_值对是为了方便。 

alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)

 

代码输出:
{'color': 'green', 'points': 5}

6.2.4 修改字典中的值
要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")

代码输出:

   The alien is green.
   The alien is now yellow.

以下是有趣的例子:
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x-position: " + str(alien_0['x_position']))
# 向右移动外星人
# 据外星人当前速度决定将其移动多远
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# 这个外星人的速度一定很快
x_increment = 3
# 新位置等于老位置加上增量
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x-position: " + str(alien_0['x_position']))
代码输出:

   Original x-position: 0
   New x-position: 2

6.2.5 删除键_值对
对于字典中不再需要的信息,可使用del 语句将相应的键—值对彻底删除。使用del 语句时,必须指定字典名和要删除的键
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)

代码输出:

  {'color': 'green', 'points': 5}
  {'color': 'green'}

   6.2.6 由类似对象组成的字典

  确定需要使用多行来定义字典时,在输入左花括号后按回车键,再在下一行缩进四个空格,指定第一个键—值对,并在它后面加上一个逗号。此后你再次按回车键时,文本编辑器将自动缩进后续键—值对,且缩进量与第一个键—值对相同。定义好字典后,在最后一个键—值对的下一行添加一个右花括号,并缩进四个空格,使其与字典中的键对齐。 

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
6.3 遍历字典
使用一个for 循环来遍历这个字典。
 
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
代码输出:   

    Jen's favorite language is Python.
    Sarah's favorite language is C.
    Edward's favorite language is Ruby.
    Phil's favorite language is Python.

 6.3.2 遍历字典中的所有键

 在不需要使用字典中的值时,方法keys() 很有用。

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print(" Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
代码输出:

   Jen
  Sarah
  Hi Sarah, I see your favorite language is C!
  Edward
  Phil
  Hi Phil, I see your favorite language is Python!

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

使用函数sorted() 来获得按特定顺序排列的键列表的副本,在for 循环中对返回的键进行排序。

favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
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.

6.3.4 遍历字典中的所有值
使用方法values() 返回一个值列表,而不包含任何键;使用集合(set)。集合 类似于列表,但每个元素都必须是独一无二的。
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())

6.4 嵌套
有时候需要将一系列字典存储在列表中,或将列表作为值存储在字典中,这称为嵌套 。
6.4.1 字典列表
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)

代码输出:

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

更符合现实的情形是,使用range() 自动生成了30个字典:
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[:5]:
print(alien)
print("...")
print("Total number of aliens: " + str(len(aliens)))
 代码输出:

  {'color': 'green', 'points': 5, 'speed': 'slow'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  ...
  Total number of aliens: 30

使用for 循环和if 语句来修改某些字典值。

aliens = []
for alien_number in range (0,30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
for alien in aliens[0:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
for alien in aliens[0:5]:
print(alien)
print("...")

代码输出:

  {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  {'color': 'yellow', 'points': 10, 'speed': 'medium'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  {'color': 'green', 'points': 5, 'speed': 'slow'}
  ...

6.4.2 在字典中存储列表

pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
print("You ordered a " + pizza['crust'] + "-crust pizza " +
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)

代码输出:

  You ordered a thick-crust pizza with the following toppings:
  mushrooms
  extra cheese

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())

代码输出:

   Jen's favorite languages are:
   Python
   Ruby

   Sarah's favorite languages are:
   C

   Edward's favorite languages are:
   Ruby
   Go

   Phil's favorite languages are:
   Python
   Haskell

6.4.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

注:我们首先定义了一个名为users 的字典,其中包含两个键:用户名'aeinstein' 和'mcurie' ;与每个键相关联的值都是一个字典,其中包含用户的名、姓和居住地。我们遍历字典users ,
让Python依次将每个键存储在变量username 中,并依次将与当前键相关联的字典存储在变量user_info 中。在主循环内部的❷处,我们将用户名
打印出来。
在处,我们开始访问内部的字典。
变量user_info 包含用户信息字典,而该字典包含三个键:'first' 、'last' 和'location' ;对于每位用户,我们都使用这些键来生成整洁的姓名和居住地,然后打印有关用户的简要信息。

 

转载于:https://www.cnblogs.com/wushuai514/p/11138534.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值