《Python编程入门到实践》第六章 字典

  1. 使用字典:在Python中,字典是一系列键–值对,每个键都与一个值相关联,可以访问键来访问相关联的值,与键相关联的值可以是数字、字符串、列表乃至字典。键和值之间用冒号分隔,而键–值对之间用逗号分隔。
  2. 访问字典的值:要获取与键相关联的值,可一次指定字典名和方括号内的键;字典中可包含任意数量的键-值对。
  3. 创建一个空字典:使用字典来存储用户提供的数据或在编写能自动生成大量键-值对代码时常定义一个空字典,例如alien_0 = {}
  4. 添加键-值对:依次指定字典名、用方括号括起来的键和相关联的值,键-值对的排列顺序与添加顺序不同,Python不关心顺序,只关心键-值之间的关联关系。
  5. 修改字典中的值
  6. 删除键-值对:对于字典中不再需要的信息,可使用del语句将相应的键-值对彻底删除,使用del语句时必须指定字典名和要删除的键。
  7. 遍历字典:鉴于字典可能包含大量数据,Python支持对字典的遍历,字典可用于以各种方式存储信息,可遍历所有键-值对、键或值。1)遍历字典里所有的键-值对:dictionary.items();2)遍历字典中所有的键:dictionary.keys();3)按顺序遍历字典中所有的键:sorted(dictionary.keys());4)遍历字典中的所有值:dictionary.values(),返回一个值列表而不包含任何键,此方法没有考虑是否重复,涉及的值很少,为了剔除重复项可使用集合set()即set(dictionary.values())。
  8. 嵌套:1)字典列表:在列表中包含大量的字典,而每个字典都包含特定对象的众多信息,在这个列表中所有字典的结构都相同,可以遍历整个列表并且以相同的方式处理其中每个字典;2)在字典中存储列表:需要在列表中一键关联到多个值得时候,可以选择在字典中嵌入一个列表;3)在字典中存储字典:内涵字典的结构都相同(不同的话for循环会更复杂一些)

动手试一试
1.使用一个字典来存储一个熟人的信息,包括名、姓、年龄和居住的城市,该字典包括键first_name、last_name、age和city。

friend = {'first_name':'Wu','last_name':'Tutu','age':'24','city':'Peking'}
print(friend)
#{'first_name': 'Wu', 'last_name': 'Tutu', 'age': '24', 'city': 'Peking'}

2.用字典来存储一些人喜欢的数字,想出5个人的名字并将这些名字用作字典中的键;想出每个人喜欢的数字并存储在字典中,打印出来并询问朋友确保数据是真实的。

dic = {'WJJ':'7','RYH':'2','YJ':'6','SBX':'8','MJ':'9'}
for order in dic:
    print(order + ', Do you like number '+dic[order]+'?')
#WJJ, Do you like number 7 ?
#RYH, Do you like number 2 ?
#YJ, Do you like number 6 ?
#SBX, Do you like number 8 ?
#MJ, Do you like number 9 ?

3.词汇表:将5个编程词汇作为词汇表中的键并将它们的含义作为值存储在词汇表中;以整洁的方式打印每个词汇的含义

dic = {'Python':'Language','Mysql':'Database','a':'A','b':'B','c':'C'}
for order in dic:
    print(order + '   ' +dic[order])
#Python   Language
#Mysql   Database
#a   A
#b   B
#c   C

4.词汇表2:根据3的代码,将其中一系列print语句替换为一个遍历字典中的键和值的循环,确定该循环正确无误后,再在词汇表中添加2个python术语,再次运行并打印。

dic = {'Python':'Language','Mysql':'Database','a':'A','b':'B','c':'C'}
for order in dic:
    print(order + '   ' +dic[order])
dic ['Linux'] = 'OS'
dic ['Pycharm'] = 'IDE'
for key,value in dic.items():
    print(key.title()+'  '+value.title())

结果:

Python   Language
Mysql   Database
a   A
b   B
c   C
Python  Language
Mysql  Database
A  A
B  B
C  C
Linux  Os
Pycharm  Ide

5.河流:创建一个字典在其中存储三条大河流及其流经的国家,其中一个键-值可能是‘nile’:‘egypt’:1)使用循环为每条河流打印一条消息,如“The Nile runs through Egypt.”。2)使用循环将字典中每条河流的名字都打印出来;3)使用循环将字典包含的每个国家的名字都打印出来

dic = {'nile':'egypt','yangzi river':'china','danube':'germany','mekong river':'myanmar','mississippi river':'america'}
for key,value in dic.items():
    print('The '+ key.title()+' runs through '+ value.title())
for river in dic.keys():
    print(river.title())
for country in dic.values():
    print(country.title())

结果:

The Nile runs through Egypt
The Yangzi River runs through China
The Danube runs through Germany
The Mekong River runs through Myanmar
The Mississippi River runs through America
Nile
Yangzi River
Danube
Mekong River
Mississippi River
Egypt
China
Germany
Myanmar
America

6.调查:在6.3.1程序中1)创建一个应该会接受调查的人员名单,其中有些人已包含在字典中,而其他人未包含在字典中;2)遍历这个人员名单,对于已参与调查的人,打印一条消息表示感谢,对于未调查的人,邀请。

favorite_languages ={'jen':'python','sarah':'c','edward':'ruby','phil':'python'}
investigator = ['jen','WJJ','Tutu','phil','Jason']

for people in investigator:
    if people in favorite_languages:
        print(people.title()+' Thanks!')
    else:
        print(people.title()+' Please join us.')

结果:

Jen Thanks!
Wjj Please join us.
Tutu Please join us.
Phil Thanks!
Jason Please join us.

7.在1编写的程序中创建两个表示人的字典,然后将这三个字典都存储在一个名为people的列表中,遍历这个列表,打印所有信息

friend1 = {'first_name':'Wu','last_name':'Tutu','age':'24','city':'Zunyi'}
friend2 = {'first_name':'Chen','last_name':'kun','age':'47','city':'Chongqing'}
people = [friend1,friend2]
for friend in people:
    print(friend)

结果:

{'first_name': 'Wu', 'last_name': 'Tutu', 'age': '24', 'city': 'Zunyi'}
{'first_name': 'Chen', 'last_name': 'kun', 'age': '47', 'city': 'Chongqing'}

8.宠物:创建多个字典,对于每个字典都使用一个宠物的名称来给它命名;在每个字典中,包含宠物的类型及其主人的名字。将这些字典存储在一个名为pets的列表中,再遍历该列表,并将宠物的所有信息都打印出来

dog1 = {'type':'Husky','name':'zongzi','owner':'WJJ'}
dog2 = {'type':'Labrador','name':'kele','owner':'Tutu'}
pets = [dog1,dog2]
for pet in pets:
    print(pet)

结果:

{'type': 'Husky', 'name': 'zongzi', 'owner': 'WJJ'}
{'type': 'Labrador', 'name': 'kele', 'owner': 'Tutu'}

9.喜欢的地方:创建一个名为favorite_places的字典,在这个字典中,将三个人的名字用作键;对于其中的每个人都存储他喜欢的1-3个地方。打印出来

favorite_places ={'WJJ':['chengdu','chongqing','xinjiang'],'RYH':['chongqing','hangzhou','xizang'],
                  'YJ':['guiyang','nanjing','beijing']}
for name,places in favorite_places.items():
    print('\n'+name.title()+"'s favorite places are:")
    for place in places:
        print(place.title())

结果:


Wjj's favorite places are:
Chengdu
Chongqing
Xinjiang

Ryh's favorite places are:
Chongqing
Hangzhou
Xizang

Yj's favorite places are:
Guiyang
Nanjing
Beijing

10.喜欢的数字:类似9,不重复
11.城市:创建一个名为cities的字典,其中将三个城市名用作键;对于每座城市都创建一个字典,并在其中包含该城市所属的国家、人口约数以及一个有关该城市的事实。在表示每座城市的字典中应包含country、population和fact等键,打印信息。

cities = {
    'chongqing':{'country':'China','population':'14 billion','fact':'123'},
    'newyork':{'country':'America','population':'7 billion','fact':'234'},
    'tokeyo':{'country':'Japan','population':'4 billion','fact':'345'}
}

for keys,values in cities.items():
    print('The city is '+ keys+' It concludes:')
    for value in values.items():
        print(value)

结果:

The city is chongqing It concludes:
('country', 'China')
('population', '14 billion')
('fact', '123')
The city is newyork It concludes:
('country', 'America')
('population', '7 billion')
('fact', '234')
The city is tokeyo It concludes:
('country', 'Japan')
('population', '4 billion')
('fact', '345')

方法二:

cities = {
    'chongqing':{'country':'China','population':'14 billion','fact':'123'},
    'newyork':{'country':'America','population':'7 billion','fact':'234'},
    'tokeyo':{'country':'Japan','population':'4 billion','fact':'345'}
}

for keys,values in cities.items():
    print('The city is '+ keys+' It concludes:')
    contry= values['country']
    population = values['population']
    fact = values['fact']
    print('country is:'+contry.title())
    print('population is:'+population)
    print('fact is:'+fact)

结果:

The city is chongqing It concludes:
country is:China
population is:14 billion
fact is:123
The city is newyork It concludes:
country is:America
population is:7 billion
fact is:234
The city is tokeyo It concludes:
country is:Japan
population is:4 billion
fact is:345

小结:在本章中学习了如何定义字典以及如何使用存储在字典的信息,如何访问和修改字典中的元素;遍历字典中的所有信息;遍历字典中所有的键-值对、所有的键和所有的值;在列表中嵌套字典;字典中嵌套列表和字典中嵌套字典。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值