字典

创建字典

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

访问字典中的值

1
2
alien_0 = {'color': 'green'} # 从0用这个索引访问
print(alien_0['color'])

输出一个字典

1
2
3
alien_0 = {'color': 'green', 'points': 5}
new_points = alien_0['points']
print("You just earned " + str(new_points) + " points!")

类似对象组成字典

1
2
3
4
5
6
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

嵌套字典

1
2
3
4
5
6
7
8
9
 把三个外星人信息的字典存储到列表
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 # 利用多重赋值把上面三个字典赋值给aliens

for alien in aliens:
print(alien) # 验证一下

在字典中存储列表

1
2
3
4
5
6
7
8
9
10
11
# 存储所点比萨的信息
pizza = {
'规格': '厚的',
'配料': ['蘑菇', '额外的 奶酪'],
}

# 概述所点的比萨
print("您点了一份" + pizza['规格'] + "-厚披萨 " +
"带有以下配料:")
for topping in pizza['配料']:
print("\t" + topping)

在字典中嵌套字典

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
users = {
'爱因斯坦': {
'名': '阿尔伯特',
'姓': '爱因斯坦',
'地点': '普林斯顿',
}, # 字典和字典中夹个逗号
'麦库里': {
'名': '玛丽',
'姓': '居里',
'地点': '巴黎',
},
}

# for 循环遍历出来以后
for username, user_info in users.items():
full_name = user_info['名'] + " " + user_info['姓']
location = user_info['地点']

# 格式化输出
print("\n名人: " + username)
print("\t全名: " + full_name.title()) # \t是给一个缩进
print("\t地点: " + location.title())

增减键值对

1
2
3
4
5
alien_0 = {'color': 'green', 'points': 5}
print("修改前", alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print("修改后", alien_0)

删除键值对

1
2
3
4
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points'] # 永久删除键对
print(alien_0)

遍历所有键值对

1
2
3
4
5
6
7
8
9
10
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name, language in favorite_languages.items():
print(name.title() + "'s favorite language is " +
language.title() + ".")

遍历字典所有值/键

遍历字典默认情况会遍历所有键

1
2
3
4
5
6
7
8
9
10
11
12
13
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for languages in favourite_languages.keys():
print(name, end=',')
for languages in favourite_languages.values():
print(languages, end=',')
for languages in favourite_languages: # 遍历所有键
print(languages, end=',')

按顺序遍历

1
2
3
4
5
6
7
8
9
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}

for name in sorted(favorite_languages.keys()):
print(name.title() + ",按a-z排序。")

在字典中存储列表并遍历

1
2
3
4
5
6
7
8
9
10
11
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 language in languages:
print("\t" + language.title())

使用range函数生成30个外星人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
aliens = []

# 创建30个绿色外星人
for alien_num in range(30):
new_alien = {
"color": "green",
"points": 5,
"speed": "slow"
}
aliens.append(new_alien)

# 显示前五个外星人
for alien in aliens[:5]:
print(alien)

# 显示创建了多少个外星人
print("创建了" + str(len(aliens)) + "个外星人")

继上使用切片修改那那三十个外星人

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
aliens = []

# 创建30个绿色外星人
for alien_num in range(30):
new_alien = {
"color": "green",
"points": 5,
"speed": "slow"
}
aliens.append(new_alien)
# 修改前五个外星人
for alien in aliens[0:5]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['points'] = '1'
alien['speed'] = 'fast'
print(aliens[0:5], end="\n" + str(len(aliens[0:5]))) # 这里测以下是否5

该字典应包含键 first_name、last_name、age 和 city。将存储在该字典中的每项信息都

打印出来

1
2
3
4
5
6
7
person = {
"first_name": "张",
"last_name": "瑞鑫",
"age": "18",
"city": '沈阳市'
}
print(person)

使用一个字典来存储一些人喜欢的数字。请想出 5 个人的名字,并将这些名字用作字典中的键;想出每个人喜欢的一个数字,并将这些数字作为值存储在字典中。打印每个人的名字和喜欢的数字。为让这个程序更有趣,通过询问朋友确保数据是真实的

1
2
3
4
5
6
7
8
9
names = {
"xzy": 1,
"zrx": 2,
"tjl": 0,
"pjr": 9
}
for k, v in names.items():
print(k, v)
print()

词汇表一、

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
spam = {
"finish": "完成",
"people": "人们",
"black": "黑色",
"white": "白色",
"purple": "紫色",
"pink": "粉色"
}
while True:
words = input("输入单词")
for k, v in spam.items():
if words not in spam:
print("没有此值")
break
if words in spam.keys():
print("回答正确")
break
if words == '退出':
break

词汇表二、

1
2
3
vocabulary = {'fast': '快', 'small': 'little', 'big': 'da', 'house': 'fangzi', 'smile': 'haha'}
for c, y in vocabulary.items():
print(c + ': ' + y)