-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6.0字典.py
More file actions
89 lines (77 loc) · 2.01 KB
/
Copy path6.0字典.py
File metadata and controls
89 lines (77 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
alien0 = {'color':'red',
'name':'benn',
'points':'5',
'blood': 10}
new_points = alien0['points']
new_name = alien0['name']
print(new_points)
print(new_name)
print(alien0['color'])
print(alien0)
#键值对的添加
alien0['xposition'] = 0
alien0['yposition'] = 25
print(alien0)
# 修改字典中的信息
x_increment = 2
alien0['xposition'] = alien0['xposition'] + x_increment
print(alien0)
print(alien0['xposition'])
# 键值对的删除
if alien0['blood'] == 10:
del alien0['blood']
print(alien0) #注意:删除的键值对永远消失了。
# 通过get()来获得字典中的值,这样避免值不存在,不会报错
cur_blood = alien0.get('blood','he is dead')
print(cur_blood)
# 再添加blood看看
alien0['blood'] = 100
cur_blood = alien0.get('blood','he is dead')
print(cur_blood)
# 字典的遍历
languages = {
'june' :'python',
'bob':'c++',
'alice':'java',
}
for name,language in languages.items():
print(f"name:{name}\n")
print(f"you use {language}\n")
# 一个简单的嵌套
letters = {
'lower':['a','b','c','d'],
'upper':['A','B','C','D']
}
for key,value in letters.items():
print(key)
for letter in value:
print(letter)
# 练习 6.11:城市 创建一个名为 cities 的字典,将三个城市
# 名用作键。对于每座城市,都创建一个字典,并在其中包含该城
# 市所属的国家、人口约数以及一个有关该城市的事实。表示每座
# 城市的字典都应包含 country、population 和 fact 等
# 键。将每座城市的名字以及相关信息都打印出来。
sh_detail = {
'cty':'China',
'pop':'3000',
'fact':'fashion',
}
hf_detail = {
'cty':'China',
'pop':'2000',
'fact':'beautiful',
}
bj_detail = {
'cty':'China',
'pop':'4000',
'fact':'police',
}
cities = {
'shangahi':sh_detail,
'hefei':hf_detail,
'beijing':bj_detail,
}
for city,detail in cities.items():
print(f"city:{city}\n")
for k,v in detail.items():
print(f"{k}:{v}\n")