alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])-------------->访问字典
print(alien_0['points'])
字典类型用大括号,里面是{‘’key‘:’value’}
添加键值
alien_0['x_position'] = 0
1、实际应用中
(1)先创建一个空字典,然后往里面放key:value
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
(2)删除
del alien_0['points']
2、遍历字典
(1)遍历字典所有内容
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():------------------------------->user.item()
print("\nKey: " + key)
print("Value: " + value)
(2) 遍历键值
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
for name in favorite_languages.keys():
prinh(‘name’)
(3)遍历值
for language in favorite_languages.values():
print(language.title())
3 嵌套
(1) 列表中嵌套字典
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)
(2)字典中嵌套列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# 概述所点的比萨
print("You 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'],
}
for name, languages in favorite_languages.items():---------->遍历字典
print("\n" + name.title() + "'s favorite languages are:")
for language in languages: --------------->遍历这个key下面的value
print("\t" + language.title())
(3)在字典中存储字典