python学习笔记:第六章 字典
2017-04-06
python学习笔记:第六章 字典
一个简单的字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
值赋给变量
new_points = alien_0['points']
print ("You just earned " + str(new_points) + " points!")
已有字典中增加键-值
alien_0['x_position'] = 0
alien_0['y_positon'] = 25
print(alien_0)
空字典增加键-值
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)
修改字典中的键-值
alien_0 = {'color': 'green'}
print("The alien is " + alien_0['color'] + ".")
alien_0['color'] = 'yellow'
print("The alien is now " + alien_0['color'] + ".")
外星人来了
位置+速度—移动至新位置。
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print("Original x_positon: " + str(alien_0['x_position']))
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
x_increment = 3
alien_0['x_position'] = alien_0['x_position'] + x_increment
print("New x_position: " + str(alien_0['x_position']))
删除键-值
alien_0 = {'color': 'greem', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)
类似键-值组成的字典
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print(favorite_languages)
print("Sarah's favorite language is " +
favorite_languages['sarah'].title() +
".")
遍历所有键-值
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print("\n Key: " + key)
print("Value: " + value)
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() + ".")
for name in favorite_languages.keys():
print(name.title())
列表中的元素是不是字典中的键?
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(name.title())
if name in friends:
print("Hi " + name.title() +
", I see your favorite language is " +
favorite_languages[name].title() + "!")
遍历所有键并排序
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(name.title() + ", thank you for taking the poll!")
遍历所有值及去掉相同值
for language in favorite_languages.values():
print(language.title())
for language in set(favorite_languages.values()):
print(language.title())
字典的列表
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)
print("...")
产生30个外星人,打印前5个
定义一个字典,包含多种参数,然后生成相同字典元素的列表
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("...")
print("Total number of aliens: " + str(len(aliens)))
修改某个字典里的键值
aliens = []
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow' }
aliens.append(new_alien)
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'yellow'
alien['speed'] = 'medium'
alien['points'] = 10
elif alien['color'] == 'yellow':
alien['color'] = 'red'
alien['speed'] = 'fast'
alien['points'] =15
for alien in aliens[:5]:
print(alien)
print("...")
在字典中存储列表
存储披萨的信息,生成一个字典,字典中的某些keys可能包含多个value(list)
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
描述所点的披萨
print("Your ordered a " + pizza['crust'] + "-crust pizza" +
"with the following toppings:")
for topping in pizza['toppings']:
print("\t" + topping)
字典中含有列表,怎样读取列表中的元素?
favorite_languages = {
'jen': ['python', 'ruby'],
'sarah': ['c'],
'edward': ['ruby', 'go'],
'phil': ['python', 'haskell'],
}
print(favorite_languages['edward'][0])
for name, languages in favorite_languages.items():
if len(languages) == 1:
print("\n" + name.title() + "'s favorit language is: " + languages[0].title())
else:
print("\n" + name.title() + "'s favorite languages are:")
for language in languages:
print("\t" + language.title())
字典中存储字典
uesrs = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in uesrs.items():
print("\n Usrname: " + username)
full_name = user_info['first'] + " " + user_info['last']
location = user_info['location']
print("\tFull name: " + full_name.title())
print("\tLocation: " + location.title())