第六章 字典
6.1字典案例:
alien_0 = {'color':'green','points':5}
6.2字典:
字典是一系列键值对 键和值关联。
键值对:两个相关联的值。
6.2.1 访问字典中的值
print(alien_0['speed'])
6.2.2添加键值对
alien_0['x_position'] = 0 alien_0['y_position'] = 25
6.2.3创建一个空字典
alien_0 = {}
6.2.4修改字典中的值
print(f"Original position :{alien_0['x_position']}") alien_0['x_position']=alien_0['x_position']+alien_0['speed']
6.2.5删除键值对
del alien_0['y_position']
6.2.6 由类似对象组成的字典
fav_lang = { 'A':'C', 'B':'PYTHON', 'C':'RUBY', 'D':'PYTHON', }
6.2.7 使用get()来访问值
get(xx1,xx2)
xx1=键值,xx2=键值未设立时的返回
6.3遍历字典
6.3.1遍历所有键值对
.items()
for key, value in fav_lang.items(): print(f"Key is : {key}") print(f"Value is: {value}")
6.3.2 遍历字典中的所有键
.keys()
for name in fav_lang.keys(): print(f"Hi!{name}!")
6.3.3 按特定顺序遍历字典中的所有键.
.sorted()
.sorted(fav_lang.keys())
6.3.4遍历字典中的所有值
for name in fav_lang.values()
不重复 set():
set(fav_lang.values()):
6.4 嵌套
6.4.1字典列表
alien_0 = {'color':'green','points':5} alien_1 = {'color':'yellow','points':25} alien_2 = {'color':'red','points':15} aliens = [alien_0, alien_1, alien_2]
6.4.2在字典中储存列表
pizza = { 'crust':'thick', 'toppings':['mushrooms','extra cheese'], } print(f"you ordered a {pizza['crust']}--crust pizza with the following toppings:") for topping in pizza['toppings']【x】选123: print(topping)
6.4.3在字典中嵌套字典