前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >21天Python进阶学习挑战赛打卡------第4天(字典)

21天Python进阶学习挑战赛打卡------第4天(字典)

作者头像
指剑
发布2022-08-26 14:58:16
8110
发布2022-08-26 14:58:16
举报
文章被收录于专栏:指剑的分享
代码语言:javascript
复制
语法:
字典名 = {'键':'值','键':'值',....}
例如:

test = {'color':'pink','points':7}
print(test['color'])
print(test['points'])

‘’’

#例2:test中的键和值不变,我们从字典中获取相关的键和值,把这个值储存在new_points中 #再如下操作中,需要将new_points的整数类型转化为字符串

代码语言:javascript
复制
new_points = test['points']
print("You just earned " + str(new_points) + "points !")

#例3、给字典添加新的键值对,键为 x_position,值为0;键为 y_position,值为25

代码语言:javascript
复制
test = {'color':'pink','points': 7 }
print(test)

test['x_position'] = 0  #给字典添加新的键值对,键为 x_position,值为0
test['y_position'] = 25 #给字典添加新的键值对,键为 y_position,值为25
print(test)

#例4:创建空字典并分别添加值

代码语言:javascript
复制
test1 = { }
#分行添加新的键值对
test1['color'] = 'blue'
test1['points'] = 5

print(test1)

#例5:更改字典中键对值内容并打印显示

代码语言:javascript
复制
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来对值判断,然后更换其中值

代码语言:javascript
复制
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语句指定字典名和要删除的键

代码语言:javascript
复制
test4{'color':'white','points':9}
print(test4)

del test4['points']  #del语句是彻底删除
print(test4)

#例8:使用多行定义字典,输入左花括号后按回车,缩进,指定键值对

代码语言:javascript
复制
test5 = {
    'name':'test5',
    'number':5,
    'power':'88W',
    }
print('The user is:' + test5['name'].title() + '.') #此处title()是将test5以标题形式展出

#例9:用for循环遍历字典,声明2个变量用来存储键和值;接下来的for循环中,python将每个键值储存在key,value2个变量中

代码语言:javascript
复制
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中

代码语言:javascript
复制
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中

代码语言:javascript
复制
favorite_languages = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python',
    }
#使用方法key()提取字典中所有的键,并把键存储到变量name中
for name in favorite_languages.key():
    print(name.title())

#例12:if 测试,判断键值对,如果名字在列表friends中,就打印一句问候语

代码语言:javascript
复制
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 !’

代码语言:javascript
复制
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列出所有键,在遍历前进行排序

代码语言:javascript
复制
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()方法提取字典的值

代码语言:javascript
复制
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循环遍历列表,打印出对应的键值对

代码语言:javascript
复制
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

代码语言:javascript
复制
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的空列表

代码语言:javascript
复制
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: #存储所有点披萨的信息

代码语言:javascript
复制
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 分别在循环中获取字典的键值对,并通过字符拼接方式重新获取新的字符串,打印出来

代码语言:javascript
复制
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 分别在循环中获取字典的键值对,并通过字符拼接方式重新获取新的字符串,打印出来

代码语言:javascript
复制
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())
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-08-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档