# 有C 和C++基础的学习笔记
# 参考书《Python编程从入门到实践》
# Python 3
# 所有代码不给出运行结果,可直接copy
示范:
# coding=utf-8
# 存储了两个 键-值对;'color'是一个键,与之相关联的值为'green'
alien_0 = {'color':'green','points':5}
# 访问字典中的值:指定字典名和放在方括号内的键;字典名:alien_0
print(alien_0['color'])
print(alien_0['points'])
字典: 键-值对。每个键都与一个值关联,与键相关联的值可以是数字,字符串,列表乃至字典。
键和值之间用":"分隔,键-值对间用","分隔。
一、添加键-值对
# coding=utf-8
alien_0 = {'color':'green','points':5}
print(alien_0)
alien_0['x_position']=0 # 新增键'x_position',值为0
alien_0['y_position']=25# 新增键'y_position',值为25
print(alien_0)
# coding=utf-8
alien_0 = {} # 创建一个空字典 alien_0
alien_0['color']='green'
alien_0['points']=5
print(alien_0)
二、修改字典中的值
# coding=utf-8
alien_0 = {'color':'green'}
print("The alien is "+alien_0['color']+'.')
alien_0['color'] = 'yellow' #将'green'修改为'yellow'
print("The alien is now "+alien_0['color']+'.')
三、删除键-值对
对于字典中不再需要的信息,可使用del语句将相应的键-值对彻底删除。
使用del语句时,必须指定字典名和要删除的键。
# coding=utf-8
alien_0 = {'color':'green','points':5}
print(alien_0)
del alien_0['points'] #删除键 'points'
print(alien_0)
四、由类似对象组成的字典
# 注意较长语句的拆分。
# coding=utf-8
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python'
}
print(favorite_languages)
print("Sarah's favorite language is "+
favorite_languages['sarah'].title()+
".")
五. 遍历字典
1. 遍历所有的键-值对
# -*- coding: gbk -*
user_0 = {
'username':'efermi',
'first':'enrico',
'last':'fermi',
}
# 声明两个变量key,value用于存储键-值对中的键和值.
# user_0.items()返回一个键-值对列表
# for循环依次将每个键-值对存储到指定的两个变量中.
for key,value in user_0.items():
print("\nKey:"+key)
print("Value:"+value)
# 遍历字典时,键-值对的返回顺序与存储顺序不同.
2. 遍历字典中的所有键
# -*- coding: gbk -*
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
# for name in favorite_languages:
for name in favorite_languages.keys():#提取字典中的所有键,并依次存储在变量name中
print(name.title())
两个for语句输出结果一样,显式使用方法keys()可使代码更容易理解.
3. 按顺序遍历字典中的所有键
以特定顺序返回元素,在for循环中对返回的键进行排序:可使用函数sorted()来获得特定顺序排列的键列表的副本.
# -*- coding: gbk -*
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
for name in sorted(favorite_languages.keys()):# 在遍历前对这个列表进行排序
print(name)
4. 遍历字典中的所有值
# -*- coding: gbk -*
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())
用方法value().
没有考虑到是否重复.
剔除重复项,使用集合(set).
集合类似于列表,但每个元素都必须是独一无二的.
# -*- coding: gbk -*
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())
六 嵌套
1. 字典列表
# coding=utf-8
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)
# coding=utf-8
# 创建一个用于存储外星人的空列表
aliens = []
#创建30个绿色的外星人
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)))
2. 在字典中存储列表
# coding=utf-8
# 存储所点比萨的信息
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'], # pizza字典中存储列表
}
# 概述所点的比萨
print("You ordered a "+pizza['crust']+'-crust pizza' +
"with the following toppings: ")
# 循环打印toppings列表中的元素
for topping in pizza['toppings']:
print("\t"+topping)
# coding=utf-8
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 language are: ") # 打印键
for language in languages: #打印值: 列表循环
print("\t"+ language.title())
修改, 使得当喜欢的语言只有一种时, 输出 "are" 变 为"is":
# coding=utf-8
favorite_languages = { # 名字-喜欢的语言
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,languages in favorite_languages.items():
if len(languages) == 1: # 添加这句确定长度
print("\n"+name.title()+"'s favorite language is: ")
print("\t"+language.title())
else:
print("\n"+name.title()+"'s favorite language are: ")
for language in languages:
print("\t"+ language.title())
3. 在字典中存储字典
# coding=utf-8
users = { #用户字典
'aeinstein':{ #用户信息字典
'first':'albert',
'last':'einstein',
'location':'priceton',
},
'mcurie':{
'first':'marie',
'last':'curie',
'location':'paris',
},
}
for username,user_info in users.items():
print("\nUse\rname: "+username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title()) # title()方法 使所有单词都以大写开头
print("\tLocation: " + location.title())
# print((user_info['first'] + " " + user_info['last']).title())