首页 > 代码库 > 2017-5-15 字典操作

2017-5-15 字典操作

alien_0 = {‘color‘:‘green‘,‘points‘:5}
print(alien_0[‘color‘])
print(alien_0[‘points‘])                                 字典格式   key:value格式

 

添加键值对:

alien_0[‘x_postion‘] = 0
alien_0[‘y_postion‘] = 25

print(alien_0)

 

删除键值对:


del alien_0[‘points‘]
print (alien_0)

 

遍历字典:

for key,value in user_0.items():
print(key)
print(value)

 

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

 

字典列表:

alien_0= {‘color‘:‘green‘,‘points‘:‘5‘}
alien_1 = {‘color‘:‘yellow‘,‘points‘:‘10‘}
alien_2 = {‘color‘:‘red‘,‘points‘:‘6‘}

aliens = [alien_0,alien_1,alien_2]

for alien in aliens:
print(alien)

 

aliens = []

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(str(len(aliens)))

 

 

pizza = {
‘crust‘:‘thick‘,
‘toppings‘:[‘extra cheese‘,‘mushrooms‘]
}

print(pizza[‘toppings‘][1])

2017-5-15 字典操作