Python 字典

本文详细介绍了Python字典的基本操作,包括创建、添加键值对、修改值、删除键值对、遍历字典、按顺序遍历键、获取所有唯一值、字典列表的使用,以及如何在字典中存储列表和字典。通过实例展示了字典的灵活性和实用性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


在Python中, 字典是一系列键-值对。每个键都与一个值相关联,你可以使用键来访问与之相关联的值。与键相关联的值可以是数字、字符串、列表乃至字典。事实上,可将任何 Python 对象用作字典中的值。

字典的每个键值 key-value 用冒号分割,每个键值对组合之间用逗号分割,整个字典包括在花括号中。一起来看下面的简单示例。

(1)字典 alien_0 存储了外星人的颜色和点数

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])  # 字典名['键名']
print(alien_0['points'])

输出:

green
5

(2)添加键-值对

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

输出:

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

(3)创建空字典

alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)

输出:

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

(4)修改字典中的值

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

输出:

The alien is green.
The alien is now yellow.

(5)删除键-值对

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

输出:

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

(6)遍历字典

user_0 = {
    'username': 'efermi',
    'first': 'enrico',
    'last': 'fermi',
}
for key, value in user_0.items():  # key,value也可以随意写任何名称
    print("\nKey: " + key)
    print("Value: " + value)

输出:

Key: username
Value: efermi

Key: first
Value: enrico

Key: last
Value: fermi

注意,即便遍历字典时,键-值对的返回顺序也可能与存储顺序不同。Python不关心键—值对的存储顺序,而只跟踪键和值之间的关联关系。

(7)遍历字典中的所有键

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in favorite_languages.keys():
    print(name.title())

输出:

Jen
Sarah
Edward
Phil

遍历字典时,会默认遍历所有的键,因此,如果将上述代码中的 for name in favorite_languages.keys(): 替换为 for name in favorite_languages:,输出将不变。

(8)按顺序遍历字典中的所有键
要以特定的顺序返回元素,一种办法是在for循环中对返回的键进行排序。为此,可使用函数sorted() 来获得按特定顺序排列的键列表的副本

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
    print(name.title() + ", thank you for taking the poll.")

输出:

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

(9)当然,也可以遍历字典中的所有值

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
    print(language.title())

输出:

Python
C
Ruby
Python

(10)这种做法提取字典中所有的值,并没有考虑是否重复。涉及的值很少时,这也许不是问题。但如果很多,最终的列表可能包含大量的重复项。为剔除重复项,可使用集合(set),集合类似于列表,但每个元素都必须是独一无二的。

favorite_languages = {
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil': 'python',
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
    print(language.title())

输出:

Python
C
Ruby

(11)字典列表(在列表中存储字典)

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}

(12)不止三个alien咋办??

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

输出:

{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...
Total number of aliens: 30

(13)在字典中存储列表

# 存储所点比萨的信息
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 pizza with the following toppings:
        mushrooms
        extra cheese

键toppings与之相关联的值是一个列表,其中存储了顾客要求添加的所有配料。

(14)在字典中存储字典

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

输出:

Username: aeinstein
        Full name: Albert Einstein
        Location: Princeton

Username: mcurie
        Full name: Marie Curie
        Location: Paris
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值