活动地址:CSDN21天学习挑战赛
学习的最大理由是想摆脱平庸,早一天就多一份人生的精彩;迟一天就多一天平庸的困扰。各位小伙伴,如果您:
想系统/深入学习某技术知识点…
一个人摸索学习很难坚持,想组团高效学习…
想写博客但无从下手,急需写作干货注入能量…
热爱写作,愿意让自己成为更好的人…
…
欢迎参与CSDN学习挑战赛,成为更好的自己,请参考活动中各位优质专栏博主的免费高质量专栏资源(这部分优质资源是活动限时免费开放喔~),按照自身的学习领域和学习进度学习并记录自己的学习过程。您可以从以下3个方面任选其一着手(不强制),或者按照自己的理解发布专栏学习作品,参考如下:
‘’’
语法:
字典名 = {'键':'值','键':'值',....}
例如:
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、给字典添加新的键值对,键为 x_position,值为0;键为 y_position,值为25
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:用if-elif来对值判断,然后更换其中值
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:用for循环遍历字典,声明2个变量用来存储键和值;接下来的for循环中,python将每个键值储存在key,value2个变量中
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:用for循环遍历字典,声明2个变量用来存储键和值,将键存储在变量name中,值存储在变量languages中
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:使用方法key()提取字典中所有的键,并把键存储到变量name中
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
#使用方法key()提取字典中所有的键,并把键存储到变量name中
for name in favorite_languages.key():
print(name.title())
#例12:if 测试,判断键值对,如果名字在列表friends中,就打印一句问候语
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:判断下列字典中的key中是否包含 erin,如果不存在即打印’Erin,Please take our poll !’
favorite_languages = {
'jen':'python',
'sarah':'c',
'edward':'ruby',
'phil':'python',
}
if 'erin' not in favorite_languages.keys():
print('Erin,Please take our poll !')
#例14:使用函数sorted对列表临时排序。让python列出所有键,在遍历前进行排序
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:注意上行代码中的 set 用集合set可以剔除重复项python,此处用values()方法提取字典的值
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:将3个字典放入列表tests中,然后使用for循环遍历列表,打印出对应的键值对
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的空列表
#创建30个红色的test
#使用函数 range()生成30个test
#创建new_test字典,包含3对键值
#显示前5个test
#显示创建多少个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字典,然后使用name,language 分别在循环中获取字典的键值对,并通过字符拼接方式重新获取新的字符串,打印出来
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字典,然后使用username,user_info 分别在循环中获取字典的键值对,并通过字符拼接方式重新获取新的字符串,打印出来
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())