python学习第六章---字典

6.1 一个简单的字典

任务:利用字典存储有关特定外星人的信息(颜色,得分)

In [1]:

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

6.2 使用字典

6.2.1 访问字典中的值

In [2]:

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

In [9]:

 
#打印射杀外星人后获得的分数
alien_0 = {'color':'green','point':5}
new_points = alien_0['point']
print(f"You just earned {new_points} points!")
You just earned 5 points!

6.2.2 添加键值对

In [14]:

 
alien_0 = {'color':'greem','point':5}
print(alien_0)
#增加外星人的x坐标y坐标
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
{'color': 'greem', 'point': 5}
{'color': 'greem', 'point': 5, 'x_position': 0, 'y_position': 25}

In [15]:

 
alien_0 = {'color':'greem','point':5,'x_position':0,'y_position':15}
print(alien_0)
{'color': 'greem', 'point': 5, 'x_position': 0, 'y_position': 15}

6.2.3 创建空字典

In [17]:

 
alien_0 = {}
alien_0['color'] = 'green'
alien_0['point'] = 0
print(alien_0)
{'color': 'green', 'point': 0}

6.2.4 修改字典中的值

In [19]:

 
alien_0 = {'color':'green','point':5}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is {alien_0['color']}.")
The alien is green.
The alien is yellow.

任务:对一个能够以不同速度移动的外星人进行位置追踪,首先存储该外星人的当前速度,并据此确定该外星人将向右移动多远

In [27]:

 
alien_0 = {'x_position':0,
          'y_position':25,
          'speed':'medium'}
print(f"Original position: {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(f"New x_position: {alien_0['x_position']}")
Original position: 0
New x_position: 2

6.2.6 由类似对象组成的字典

字典信息可以储存一个对象的多个信息 字典也可以存储多个对象的同一个信息

In [43]:

 
favorite_languages={
    'jen':'python',
    'sarah':'c',
    'edvard':'ruby',
    'phil':'python'
}
for name,language in favorite_languages.items():
    print(f"{name.title()}'s favorite language is {language.title()}.")
Jen's favorite language is Python.
Sarah's favorite language is C.
Edvard's favorite language is Ruby.
Phil's favorite language is Python.

6.2.7 使用get来访问值

使用alien_0.get()代替print(alien_0[])

In [34]:

 
alien_0 = {'color':'green','speed':'slow'}
point_value = alien_0.get('point')
print(point_value)
None

In [36]:

 
alien_0 = {'color':'green','speed':'slow'}
point_value = alien_0['point']
print(point_value)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [36], in <cell line: 2>()
      1 alien_0 = {'color':'green','speed':'slow'}
----> 2 point_value = alien_0['point']
      3 print(point_value)

KeyError: 'point'

6.3 遍历字典

遍历所有键值对--dict.items()

In [38]:

 
user_0 = {
    'username':'eferni',
    'first':'enrico',
    'last':'ferni',
}
for key,value in user_0.items():
    print(f"\nKey:{key}")
    print(f"Value:{value}")
Key:username
Value:eferni

Key:first
Value:enrico

Key:last
Value:ferni

6.3.2 遍历所有键--dict.keys()

In [1]:

 
favorite_languages = {
    'jens':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name in favorite_languages.keys():
    print(name.title())
Jens
Sarah
Edward
Phil

遍历字典时,会默认遍历所有的健。即for name in favorite_languages.keys():可替换为for name in favorite_languages:

In [5]:

 
favorite_languages = {
    'jens':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_languages.keys():
    print(f"Hi {name.title()}.")
 
    if name in friends:
        language = favorite_languages[name].title()
        print(f"\t{name.title()},I see you love {language}!")
Hi Jens.
Hi Sarah.
	Sarah,I see you love C!
Hi Edward.
Hi Phil.
	Phil,I see you love Python!

6.3.3 按特定顺序遍历字典中的所有健

In [6]:

 
favorite_languages = {
    'jens':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for name in sorted(favorite_languages.keys()):
    print(f"{name.title()},thank you for taking the poll.")
Edward,thank you for taking the poll.
Jens,thank you for taking the poll.
Phil,thank you for taking the poll.
Sarah,thank you for taking the poll.

6.3.4 遍历字典中的所有值

In [7]:

 
favorite_languages = {
    'jens':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for language in favorite_languages.values():
    print(language.title())
Python
C
Ruby
Python

set可保证每个元素是独一无二的

In [9]:

 
favorite_languages = {
    'jens':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
}
for language in set(favorite_languages.values()):
    print(language.title())
Ruby
Python
C

6.4 嵌套

6.4.1 字典列表

In [19]:

 
aliens = []
for alien_number in range(30):
    new_alien = {'color':'green','point':5,'speed':'slow'}
    aliens.append(new_alien)
for alien in aliens[:5]:
    print(alien)
print("...")
print(f"Total number of aliens:{len(aliens)}")
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
{'color': 'green', 'point': 5, 'speed': 'slow'}
...
Total number of aliens:30

In [20]:

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

6.4.2 在字典中存储列表

In [24]:

 
pizza = {
    'crust':'thick',
    'toppings':['mushrooms','extra cheese'],
}
print(f"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

In [29]:

 
favorite_languages = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
    print(f"\n{name.title()}'s favorite languages are:")
    for language in languages:
        print(f"\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 在字典中存储字典

In [2]:

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

Username:mcurie
	Full name:Mariecurie
	Location:Paris
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值