python 坚持下来会更好

python 坚持下来会更好

第六章字典

6.1一个简单的字典

eg

alien.py

alien_0={‘color’:green,’points’:5}

print(alien_0[‘color’])

print(alien_0[‘points’])

# 字典使用的格式 字典名={'’:  ,’’: }且字典是一对键值对。

6.2字典使用

# 与键相关的值可以是数字、字符串、列表乃至字典。

# 键-值对之间用逗号隔开。

6.2.1访问字典中的值

alien_0={‘color’:green,’points’:5}

new_points = alien_0[‘points’]

print(“you just earned” + str(new_points) +”points”))

# 代码段杀死机器人 获得5点积分

6.2.2添加键-值对

eg:

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,’y_postion’:25,’x_postion’:0}

6.2.3创建一个空字典

alien_0={}

alien_0[‘color’]=’green’

alien_0[‘postion’]=5

修改字典中的值

alien_0={‘color’:green,’points’:5}

alien_0[‘color’]=’yellow’

# 也可以添加速度

alien_0[speed]=’fast’

删除键值对

del alien_0[‘color’]

# 输出之后只有 points

6.3字典的遍历

eg

user_0={

   ‘usename’:’efermi’,

   ‘first’:’enrico’,

   ‘last’:’fermi’,

   }

for key,value in user_0.items():

     print(“ key:”+key)

     print(“Value:”+value)

# 遍历字典所以值

for name in user_0.keys():
   print(name.title)

#方法 .items()和.keys()(返回一个列表)还有.values()

6.3.3按顺序遍历

for 变量名(新) in sorted(变量名(原).keys()):

6.4嵌套

eg:

   alien.py

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)

# 也可以使用range()函数随机生成

eg

#创建一个用于储存外星人的空列表

aliens =[]

#创建30个绿色的外星人
 for alien_number in range(30):

new_alien={‘color’:’gree’,’points’:5,’speed’:slow’}

   aliens.append(new_aliens)

#显示前五个外星人

for alien in aliens[:5]

   print(alien)

print(“…”)

#显示创建了多少个外星人

print(“Total number of aliens:”+str(len(aliens)))

#字典中存列表和字典

注意格式

 

 

 

 

 

我只是缺少生活的动力和希望。
原文地址:https://www.cnblogs.com/9a3a/p/9710547.html