Python自学之旅 字典 ———【2022.09.12】

第六章字典

一、简单字典

输入:

alien={'color': 'green','points':'5'}
print(alien['color'])
print(alien['points'])

输出:

green
5

二、使用字典

1、访问字典中的值

alien={'color': 'green','points':'5'}
new_points=alien['points']
print("You earned "+str(new_points)+" points!")

2、添加键—值对

输入:

alien={'color': 'green','points':'5'}
print(alien)
alien['x_position']=0
alien['y_position']=25
print(alien)

输出:

{'color': 'green', 'points': '5'}
{'color': 'green', 'points': '5', 'x_position': 0, 'y_position': 25}

3、创建一个空字典

输入:

# 创建一个空字典
aline_0={}
print(aline_0)
aline_0['color']='blue'
aline_0['points']=5
print(aline_0)

输出:

{}
{'color': 'blue', 'points': 5}

4、修改字典中的值

输入:

aline_0['color']='blue'
print(aline_0['color'])
aline_0['color']='green'
print(aline_0['color'])

输出:

blue
green

有趣的例子
输入:

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']))

输出:

Original X-position: 0
New x-position: 2

5、删除键值对

输入:

alien_0={'color':'blue','points':5}
print(alien_0)
del alien_0['color']
print(alien_0)

输出:

{'color': 'blue', 'points': 5}
{'points': 5}

三、遍历字典

可以通过Keys,values,items分别获得字典的不同内容列表

1、遍历所有的键-值对

1、字典 items() 函数
以列表返回可遍历的(键, 值) 元组数组,可以用于 for 来循环遍历;

items() 方法把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回。
输入:

user_0={
    'username':'efermi',
    'first': 'enrico',
    'last':'fermi'
}
for key,value in user_0.items():
    print("\nKey: "+key)
    print("\nValue "+value)

输出:

Key: username

Value efermi

Key: first

Value enrico

Key: last

Value fermi

2、遍历字典中的所有键

输入:

user_0={
    'username':'efermi',
    'first': 'enrico',
    'last':'fermi'
}
for key in user_0.keys():
    print("\nKey: "+key)

输出:

Key: username

Key: first

Key: last

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

输入:

favorite_languages= {
    'Jen': 'python',
    'Sarah': 'C',
    'Edward': 'ruby',
    'Phil': 'python'
}
for key in sorted(favorite_languages.keys()):
    print(key)

输出:

Edward
Jen
Phil
Sarah

4、遍历字典中所有值

输入:

favorite_languages= {
    'Jen': 'python',
    'Sarah': 'C',
    'Edward': 'ruby',
    'Phil': 'python'
}
for values in favorite_languages.values():
    print(values.title())

输出:

Python
C
Ruby
Python

上述策略涉及值很少时不是任何问题,但是如果调查者很多时最终列表中会有大量重复的,为了剔除重复项,可以使用集合set。set类类似于列表,创建用{}创建,其中的元素是独一无二的,将自动剔除重复项,可以利用set([])去除列表中的重复项。

输入:

for values in set(favorite_languages.values()):
    print(values.title())

输出:

Python
C
Ruby

四、嵌套

1、字典列表

输入:

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)

输出:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

用字典存储一个机器人的各个信息,用列表存储所有机器人。But机器人不只是三个;所以说机器人要通过代码自动生成
输入:

#创建一个用于存储外星人的空列表
aliens=[]
# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'solw'}
    aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[:5]:
    print(alien)
print("....")
print(str(len(aliens)))

输出:

{'color': 'green', 'points': 5, 'speed': 'solw'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
....
30

针对不同外星人做出不同的更改
输入:

#创建一个用于存储外星人的空列表
aliens=[]
# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien={'color':'green','points':5,'speed':'solw'}
    aliens.append(new_alien)
# 显示前五个外星人
for alien in aliens[0:3]:
    if alien['color']=='green':
        alien['color']='yellow'
        alien['speed']='medium'
        alien['points']=10
# 显示前五个外星人
for  alien in aliens[:5]:
    print(alien)
print("....")
print(str(len(aliens)))

输出:

{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'yellow', 'points': 10, 'speed': 'medium'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
{'color': 'green', 'points': 5, 'speed': 'solw'}
....
30

2、在字典中存储列表

输入:

# 存储所点披萨的信息
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)

输出:

You ordered a thick-crust pizzawith the following toppings:
	mushrooms
	extra cheese

输入:

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 languages are:")
    for languages in languages:
        print("\t"+languages.title())

输出:

Jen's favorite languages are:
	Python
	Ruby

Sarah's favorite languages are:
	C

Edward's favorite languages are:
	Ruby
	Go

Phil's favorite languages are:
	Python
	Haskell

3、在字典中存储字典

输入:

user ={
    'aeinstein':{
        'first':'albert',
        'last':'einstein',
        'location':'princeton'
    },
    'mcurie':{
        'first':'marie',
        'last':'curie',
        'location':'paris',
    }
}
for username,user_info in user.items():
    print("Username:"+username)
    full_name=user_info['first']+" "+user_info['last']
    location =user_info['location']
    print("full_name:" + full_name)
    print("location:" + location)

输出:

Username:aeinstein
full_name:albert einstein
location:princeton
Username:mcurie
full_name:marie curie
location:paris
                                                                                 更新于2022/09/14
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值