第6章 字典

第6章 字典

python编程从入门到实践笔记

1.字典使用

字典定义

字典是一系列键值对,每个键都与一个值相关联,可将任何python对象用作字典中的值

alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}

在python中,字典用放在{}中的一系列键值对表示

访问字典中的值
alien_0 = {'color':'green'}
print(alien_0['color'])
添加键值对
>>> alien_0 = {'color':'green'}
>>> print(alien_0['color'])
green
>>> alien_0['love']='kai'#添加键值对
>>> alien_0['you']='chen'#添加键值对
>>> print(alien_0)
{'color': 'green', 'love': 'kai', 'you': 'chen'}#按照定义顺序打印

字典中元素的顺序与定义时相同,与添加时顺序相同

修改字典中的值

依次指定字典名、用方括号括起的键,以及与该键相关联的新值

alien_0 = {'color':'green'}
print(alien_0['color'])
alien_0['color']='yellow'
print(alien_0)
删除键值对

使用del语句指定字典名和要删除的键,删除的键值对会永远消失

del alien_0['love']
print(alien_0)
由类似对象组成的字典
favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
    }
使用get()来访问值
point_value = alien_0.get('point','no point value assigned')

如果指定键有可能不存在,应考虑使用方法get(),如果字典中有值,则返回改值,如果没有,将获得指定的默认值。

调用get()时,如果没有指定第二个参数且指定的键不存在,python将返回值None。

2.遍历字典

遍历所有键值对

使用for循环遍历整个字典,在字典名后加上.item()

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

for key, value in user_0.items():#key value 可以使用任意名字
    print(f"\nKey: {key}")
    print(f"Value: {value}")
遍历字典中的所有键

前提:不需要使用字典中的值时,使用方法keys()

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

friends = ['phil', 'sarah']
for name in favorite_languages.keys():
    print(name.title())

遍历字典时,会默认遍历所有的键

方法keys()并非只能用于遍历,将返回一个列表,其中包含字典中的所有键。

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

遍历字典时将按插入的顺序返回其中的元素

for name in sorted(favorite_languages.keys()):
    print(f"{name.title()},thank you for taking the poll")
遍历字典中的所有值

使用方法values()返回一个值列表,不包含任何键

集合(set)用于剔除重复项,集合中的每个元素都必须是独一无二的

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

关于集合

可以使用一对花括号直接创建集合,并在其中用逗号分隔元素:

>>> languages = {'python','c','c'}
>>> languages
{'c', 'python'}

tips:当花括号内没有键值对时,定义的很可能是集合。不同于列表和字典,集合不会以特定的顺序存储元素

3.嵌套

将一系列字典存储在列表中,将列表作为值存储在字典中,称为嵌套

字典列表

列表中的元素是字典

alien_0 = {
    'color':'green',
    'points':5
}
alien_1 = {
    'color':'green',
    'points':5
}
aliens = [alien_0,alien_1]
for alien in aliens:
    print(alien)
# Make an empty list for storing aliens.
aliens = []

# Make 30 green aliens.
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[:3]:
    if alien['color'] == 'green':
        alien['color'] = 'yellow'
        alien['speed'] = 'medium'
        alien['points'] = 10
    
# Show the first 5 aliens.
for alien in aliens[:5]:
    print(alien)
print("...")

print(f"Total number of aliens:{len(aliens)}")

在字典中存储列表

将字典键值对的值换成列表,每当需要在字典中将一个键关联到多个值时,都可以在字典中嵌套一个列表。

 # Store information about a pizza being ordered.
pizza = {
    'crust': 'thick',
    'toppings': ['mushrooms', 'extra cheese'],
    }

# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza "
    "with the following toppings:")

for topping in pizza['toppings']:
    print("\t" + topping)

在字典中存储字典

users = {
    'aeinstein': {
        'first': 'albert',
        'last': 'einstein',
        'location': 'princeton',
        },

    'mcurie': {
        'first': 'marie',
        'last': 'curie',
        'location': 'paris',
        },

    }

for username, user_info in users.items():
    print(f"\nUsername: {username}")
    full_name = f"{user_info['first']} {user_info['last']}"
    location = user_info['location']

    print(f"\tFull name: {full_name.title()}")
    print(f"\tLocation: {location.title()}")

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱笑的刺猬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值