字典
基本概念
alien = {'color':'green','point':5}
print(alien['color']) # 'green'
- 字典用花括号**{}**括起来,里面是字典的具体内容
- 字典的内容由**键-值对(key-value)**构成,键在前,值在后,中间用冒号分开,键-值对之间用逗号分开
- 每一个键都有与之对应的值,值可以是python中的任何对象,如字符串,数字,列表甚至字典
- 通过使用键来访问值
基本操作
增删改查
alien = {} # 创建一个空字典
alien['color'] = 'green'
alien['points'] = 5 # 字典中增加键-值对
print(alien) # {'color':'green','points':5}
del alien['color'] # 删除键-值对,永远消失
alien['points'] = 7 # 修改键对应的值,与列表修改方法类似,此处以键代替元素索引
print(aline['points']) # 查字典中的值,7
多对象字典
favorite_language = { # 字典内含有多个对象的特点
'jen':'java',
'mike':'c',
'steven':'python'
}
print('jen favorite language is:' +
favorite_language['jen'] +
'.') # 语句跨行时,需在结尾添加‘+’号,回车之后缩进至上一行相同
课后习题
6-1人
person = {'first_name':'bryant','last_name':'kobe','age':30,'city':'Los Angeles'}
print(person['first_name'])
print(person['last_name'])
print(person['age'])
print(person['city'])
6-2喜欢的数字
favorite_num = {'jordan':23,'kobe':24,'rose':1,'paul':3,'paker':9}
print('jordan favorite number is ' + str(favorite_num['jordan']))
# 注意打印时值为整数型,需要转化为字符串型(str)
6-3词汇表
vacabulary = {'del':'delete','lower':'all become lowercase','upper':'all become capital'}
print('del:' + vacabulary['del'] + '\n\n' + 'lower:' + vacabulary['lower'] + '\n\n' + 'upper:' + vacabulary['upper'])
遍历
遍历字典
格式:for key,value in 字典.items():
结果:返回一个键-值对列表
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python'
}
for key,value in favorite_language.items():
print('\nkey:' + key)
print('value:' + value)
遍历键
格式:for key in 字典.keys():
作用:返回字典中所有的键
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python'
}
for name in favorite_language.keys():
print(name) # 提取所有的键存放到变量name中,此种表达更为清晰易懂
for name in favorite_language:
print(name) # 因为遍历字典时首先默认遍历键,因此输出不变
# 例题,针对friend列表中的人进行描述,不在该列表的只打印名字
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python'
}
friends = ['jen','steven']
for name in favorite_language.keys():
if name in friends:
print('hello,' + name.title() + ' you favorite language is ' + favorite_language[name].title())
else:
print(name.title())
值得注意的是,字典中的键-值对不是按照某种特定的顺序排列的,因此在打印的时候也不会按照顺序打印,如果想要以特定的顺序进行打印,可使用函数sorted()
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python'
}
for name in sorted(favorite_language.keys()): # 按照升序进行打印
print(name)
遍历值
格式:for value in 字典.values():
作用:返回字典中所有的值
注意:值可能存在相等的情况,因此采取对提取出的数据调用集合(set()),集合的特点是值只能出现一次
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python'
'kathy':'java'
}
for language in favorite_language.values():
print(language) # 此处打印的值有重复项'java'
for language in set(favorite_language.values()):
print(language) # 调用集合之后不会出现重复项
课后习题
6-4词汇表
vacabulary = {'del':'delete','lower':'all become lowercase','upper':'all become capital'}
for term,explanation in vacabulary.items():
print('\nkey:' + term)
print('explanation:' + explanation)
6-5河流
rivers = {'nile':'egypt','yangtze':'china','ganges':'india'}
for river in rivers:
print('The ' + river.title() + ' runs through ' + rivers[river].title())
rivers = {'nile':'egypt','yangtze':'china','ganges':'india'}
for river in rivers.keys():
print(river.title())
rivers = {'nile':'egypt','yangtze':'china','ganges':'india'}
for nation in rivers.values():
print(nation.title())
6-6调查
favorite_language = {
'jen':'java',
'mike':'c',
'steven':'python',
'kathy':'java'
}
investigation_persons = ['jen','jessi','kathy','gary'] # 创建人员名单
for investigation_person in investigation_persons:
if investigation_person in favorite_language.keys():
print('thank you for investigation')
else:
print(investigation_person + ' we are glad to invite you to our investigation')
嵌套
基本含义
将列表和字典以任意组合存储,称之为嵌套,如在列表中存储字典或列表,在字典中存储字典或列表
字典列表
含义:同时处理多个字典,每个字典又包含多个特征,如同时对屏幕上的外星人进行处理,每个外星人又有不同的颜色,不同的分值,由此产生一个字典列表
alien_0 = {'color':'green','point':5}
alien_1 = {'color':'red','point':10}
alien_2 = {'color':'yellow','point':15} # 对每个外星人创建字典
aliens = [alien_0,alien_1,alien_2] # 创建字典列表
for alien in aliens: # 遍历列表
print(alien)
aliens = []
for new_alien in range(30): # 产生30个外星人
new_alien = {'color':'green','speed':'slow','point':5} # 刻画每个外星人的特性
aliens.append(new_alien) # 将每一个外星人加入到列表中
for alien in aliens[0:3]: # 选取前三个外星人进行修改特性
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['point'] = 10
for alien in alien[0:3]: # 将每个字典看作一个元素进行打印
print(alien)
字典中存储列表
层层剥离,先将字典中的键和值剥离,再将剥离出来的值当作一个列表进行处理
favorite_languages = {
'jen':['java','php'],
'mike':['c','python'],
'steven':['c++','python'],
'kathy':['java','c#']
}
for name,languages in favorite_languages.items(): # 将键和值分开装进两个变量
print(name.title())
for language in languages: # 对值的变量进行处理
print(language)