#字典
‘’’
语法:
字典名 = {'键':'值','键':'值',....}
例如:
test = {'color':'pink','points':7}
print(test['color'])
print(test['points'])
‘’’
#例2:test中的键和值不变,我们从字典中获取相关的键和值,把这个值储存在new_points中
#再如下操作中,需要将new_points的整数类型转化为字符串
new_points = test['points']
print("You just earned " + str(new_points) + "points !")
#例3
test = {'color':'pink','points': 7 }
print(test)
test['x_position'] = 0 #给字典添加新的键值对,键为 x_position,值为0
test['y_position'] = 25 #给字典添加新的键值对,键为 y_position,值为25
print(test)
#例4:创建空字典
test1 = { }
#分行添加新的键值对
test1['color'] = 'blue'
test1['points'] = 5
print(test1)
#例5:更改字典中键对值内容
test2 = {'color':'red'}
print('The color is ' + test2['color'] + '.')
#将red修改为pink
test2['color'] = 'yellow'
print("The test2 new color is " + test2['color'] + '.')
#例6:
test3 = {'x_position':0,'y_position':25,'speed':'medium'}
print('Original x-position:' + str(test3['x_position']) )
#向右移动test
#据外星人当前速度决定将其移动多远
if test3['speed'] == 'slow':
x_increment = 1
elif test3['speed'] = 'medium':
x_increment = 2
else:
# test3 速度过快
x_increment = 3
test3['x_position'] = test3['x_position'] + x_increment
print('New x-position:' + str(test3['x_position']))
#例7:删除键值,使用del语句指定字典名和要删除的键
test4{'color':'white','points':9}
print(test4)
del test4['points'] #del语句是彻底删除
print(test4)
#例8:使用多行定义字典,输入左花括号后按回车,缩进,指定键值对
test5 = {
'name':'test5',
'number':5,
'power':'88W',
}
print('The user is:' + test5['name'].title() + '.') #此处title()是将test5以标题形式展出
#例9:
test6 = {
'username':'test6',
'first':'t',
'last':6,
}
#用for循环遍历字典,声明2个变量用来存储键和值,
#接下来的for循环中,python将每个键值储存在key,value2个变量中
for k,v in test6.items():
print("\nKey:" + k)
print("Value:" + v)
#例10:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#用for循环遍历字典,声明2个变量用来存储键和值,
#将键存储在变量name中,值存储在变量languages中
for name,language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")
#例11:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#使用方法key()提取字典中所有的键,并把键存储到变量name中
for name in favorite_languages.key():
print(name.title())
#例12:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
friends = ['phil','sarah']
for name in favorite_language.keys():
print(name.title())
if name in friends:
#if 测试,如果名字在列表friends中,就打印一句问候语
print('Hi' + name.title() + ', I see your favorite language is' + favorite_languages[name].title() + '!')
#例13:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print('Erin,Please take our poll !')
#例14:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#使用函数sorted对列表临时排序。让python列出所有键,在遍历前进行排序
for name in sorted(favorite_languages.keys()):
print(name.title() + ', thank you for taking the poll .')
#例15:
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
print('The follwing language have been memtioned :')
for language in set favorite_languages.values():
#注意上行代码中的 set 用集合set可以剔除重复项python
#此处用values()方法提取字典的值
print(language.title())
#例16:
test_1 = {'color':'white','point':5}
test_2 = {'color':'pink','point':6}
test_3 = {'color':'blue','point':8}
#将3个字典放入列表tests中
tests = [test_1,test_2,test_3]
#使用for循环遍历列表
for test in tests:
print(test)
#例17:
#创建一个用于储存test的空列表
tests = []
#创建30个红色的test
#使用函数 range()生成30个test
for test_number in range(30):
#创建new_test字典,包含3对键值
new_test = {'color':'red','points':5,'speed':'slow'}
tests.append(new_test)
#显示前5个test
for test in tests[:5]:
print(test)
print('...')
#显示创建多少个test
print('Total number of tests:' + str(len(aliens)))
#例18:
#创建一个用于储存test的空列表
tests = []
#创建30个红色的test
#使用函数range()打印0-29
for test_number in range(0,30):
#创建new_test字典,包含3对键值
new_test = {'color':'red','points':5,'speed':'slow'}
tests.append(new_test)
#for循环,指定索引0-3,也就是元素0 1 2
for test in tests[0:3]:
#使用if进行测试,检查键是否等于red,如果通过,执行if测试后面缩进的代码
if test['color'] == 'red':
test['color'] = 'yellow'
test['speed'] = 'medium'
test['points'] = 10
#显示前5个test
for test in tests[:5]:
print(test)
print('...')
#例19:
#存储所有点披萨的信息
pizza = {
'crust':'thick',
'toppings':['mushrooms','extra cheese'], #此处在字典中嵌套列表
}
#概述所点的披萨
print('You ordered a ' + pizza['crust'] + '-crust pizza' +
'with the following toppings:')
for topping in pizza['toppings']:
print('\t' + topping)
#例20:
favorite_language = {
'jen':['python','ruby'],
'sarah':['c'],
'edward':['ruby','go'],
'phil':['python','haskell'],
}
for name,language in favorite_languages.items():
print('\n'+ name.title() + "'s favorite languages are:")
for language in languages:
print('\t' + language.title())
#例21:
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())