Python练习:从入门到实践——字典

目录

一、简单的字典

二、使用字典

2.1  访问字典

2.2 添加键-值对

2.3 先创建一个空字典

2.4 修改字典中的值

2.5 删除 键—值对

2.6 由类似对象组成的字典

三、遍历字典

3.1 遍历所有的键—值对

3.2 遍历字典中的所有键

3.3 按顺序遍历字典中的所有键

3.4 遍历字典中的所有值

四、嵌套

4.1 字典列表

4.2 在字典中存储列表

4.3 在字典中存储字典


一、简单的字典

alien_0={'color':'green','points':5}

print(alien_0['color'])
print(alien_0['points']

二、使用字典

  • 字典由一系列“键-值对”组成,每一个键都与一个值相关联,使用“键”来访问“值”
  • “值”可以是数字、字符串、列表、字典...
  • 键 值之间用:分隔,键-值对之间用,分隔

2.1  访问字典

alien_0['color']

2.2 添加键-值对

alien_0 = {'color':'green','points':5}
print(alien_0)

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

2.3 先创建一个空字典

alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5

print(alien_0)

2.4 修改字典中的值

e.g.1 修改颜色值

alien_0 = {'color':'green'}
print("The alien is " + alien_0['color'] + ".")

alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")

e.g.2 if-elif-else 修改值

# -*- coding:utf-8 -*-

alien_0 = {'x_position':0,'y_position':25,'speed':'medium'}
print("Original x-position: " + str(alien_0['x_position'])

# 向右移动外星人
# 据外星人当前速度决定移动的距离
if alien_0['speed'] == 'slow':
    x_increment = 1
elif alien_0['speed'] == 'medium':
    x_increment = 2
else:
    x_increment = 3

alien_0['x_position'] = alien_0['x_position'] + x_increment

print("New x-position: " + str(alien_0['x_position']))

2.5 删除 键—值对

使用del 语句,指出字典名和键名。 (删除的键—值对没有备份,永远消失)

del alien_0['points']

2.6 由类似对象组成的字典

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }
print("Sarah's favorite language is " +
      favorite_language['sarah'].title() +
      ".")

三、遍历字典

3.1 遍历所有的键—值对

user_0 = {
    'username':'efermi',
    'first':'enrico',
    'last':'fermi'
    }

for key, value in user_0.items():
    print("\nKey: " + key)
    print("Value: " + value.title())

⚠️ 遍历顺序与存储顺序可能不同。python不关心键—值对的存储顺序,只跟踪键与值之间的关联关系。

3.2 遍历字典中的所有键

# -*- coding: utf-8 -*-
favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }
friends = {'phil','sarah'}

# 可以省略keys()
# for name in favorite_language:
for name in favorite_language.keys():
    print(name.title())
    if name in friends:
        print("Hi! " + name.title() + ", I see your favorite language is " +                    
              favorite_language[name].title() + ".") 

if 'erin' not in favorite_language.keys():
    print("Erin, please take our poll!")

3.3 按顺序遍历字典中的所有键

在 for 循环中对返回的键进行排序。

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }

# 首字母正序
for name in sorted(favorite_language.keys()):
    print(name.title() + ", thank you for taking our poll!")

# 首字母倒序
for name in sorted(favorite_language.keys(), reverse = True):
    print(name.title() + ", thank you for taking our poll!")

3.4 遍历字典中的所有值

values() 得到字典中的值,使用方法set() 剔除重复项。

favorite_language = {
    'jen':'python',
    'sarah':'c',
    'edward':'ruby',
    'phil':'python'
    }

for name in sorted(favorite_language.keys(), reverse = True):
    print(name.title() + ", thank you for taking our poll!")

print("\n")
for language in favorite_language.values():
    print(language.title())

print("\n剔除重复项")
# set()
for language in set(favorite_language.values()):
    print(language)

四、嵌套

列表嵌套字典;字典嵌套字典;字典嵌套列表...

4.1 字典列表

# 创建一个用于存储外星人的空列表
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)))

4.2 在字典中存储列表

favorite_language = {
    'jen':['python','ruby'],
    'sarah':['c'],
    'edward':['ruby','go'],
    'phil':['python','haskell']
    }

for name, languages in favorite_language.items():
    if len(languages) == 1:
        print("\n" + name.title() + "'s favorite language is " )
        print("\t" + str(languages[0].title()))
    else:
        print("\n" + name.title() + "'s favorite language are ")
        for language in languages:
            print("\t" + language.title())

4.3 在字典中存储字典

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())

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值