【Python笔记】第6章 字典

1.使用字典

字典可存储的信息量几乎不受限制。
在Python中,字典是一系列 键-值对。每个都与一个相关联,你可以使用来访问与之相关联的
字典用放在花括号{ }中的一系列键-值对表示。

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

1.1访问字典中值

依次指定字典名和放在方括号内的键。

alien_0={'color':'green','points':'5'}
new_points=alien_0['points']
print("You just earned "+str(new_points)+" points!")
#You just earned 5 points!

1.2添加键-值对

字典是一种动态结构,可随时增加键-值对。依次指定字典名、用方括号括起的键和相关联的值。

alien_0={'color':'green','points':'5'}
alien_0['x_position']=0
alien_0['y_position']=25
print(alien_0)
#{'color': 'green', 'points': '5', 'x_position': 0, 'y_position': 25}

1.3创建一个空字典

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

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

1.4修改字典中的值

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

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

1.5删除键-值对

del语句将相应的键-值对彻底删除。使用时,必须指定字典名和要删除的键。

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

1.6较大的字典放多行

favorite_languages={
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }

print("Sarah's favorite language is "+
      favorite_languages['sarah'].title()+
      "."
      )
#Sarah's favorite language is C.

2.遍历字典

2.1遍历所有的键-值对items()

使用for循环遍历这个字典。键-值对的返回顺序与存储顺序不同。Python不关心键-值对的存储顺序,只跟踪键和值之间的关联关系。
items()返回一个键-值对列表。

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

Key: first
Value: enrico

Key: last
Value: fermi

2.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
 HiSarah, I see your favorite language is C!
Edward
Phil
 HiPhil, I see your favorite language is Python!

2.3按顺序遍历所有的键sorted()

在for循环中对返回的键进行排序。按照字母顺序。

favorite_languages={
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
for name in sorted(favorite_languages.keys()):
    print(name.title()+", thank u for taking the poll."
#Edward, thank u for taking the poll.
#Jen, thank u for taking the poll.
#Phil, thank u for taking the poll.
#Sarah, thank u for taking the poll.

2.4遍历所有值values()

使用values(),返回一个值列表,而不包含任何键。

favorite_languages={
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())
#结果
The following languages have been mentioned:
Python
C
Ruby
Python

为剔除重复项,可使用集合set()。

avorite_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())
 #结果
The following languages have been mentioned:
Python
Ruby
C

3.嵌套

将一系列字典存储在列表中,或将列表作为值存储在字典中,称为嵌套。

3.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'}
aliens=[]
#创建30个绿色的外星人

for alien_number in range(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
#显示前5个外星人
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'}
...

3.2在字典中存储列表

每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

#存储所点披萨的信息
pizza = {
       'crust': 'thick',
       'toppings': ['mushrooms','extra cheese'],
       }
#概述所点的披萨
print("You order a "+pizza['crust']+"-crust pizza "+
      "with the following toppngs:")
for topping in pizza['toppings']:
    print("\t"+topping)
#结果
You order a thick-crust pizza with the following toppngs:
        mushrooms
        extra cheese

3.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、付费专栏及课程。

余额充值