字典是由一系列的键值对组成
dic = { 'a' : 0, 'b' = '你好'}
访问字典中的值
指定字典名和放在方括号内的键
alint = {'color':'blue', 'points':5}
print(alint['color'])
blue
添加键值对
指定字典名,用方括号的键和关联的值即可
alint = {'color':'blue', 'points':5}
print(alint['color'])
alint['weight'] = 150
alint['longth'] = 156
print(alint)
修改字典中的值
直接赋予新值即可
alint = {'color':'blue', 'points':5}
print(alint['color'])
alint['weight'] = 150
alint['longth'] = 156
print(alint)
alint['weight'] = 140
print(alint)
删除键值对
使用del语句将键值对彻底删除
del alint['color']
print(alint)
遍历字典
遍历所有键值对 ----遍历字典要包含字典名和方法items()
dic={'first_name':'du',
'last_name':'yu',
'age':18 ,
'city': 'china'}
print(dic)
for key,value in dic.items():
print ('\n'+ key)
print(value)
遍历字典中所有键
不需要值时,要用到keys()
for key in dic.keys():
print (key)
按顺序遍历字典中的所有键
用sorted()
for key in sorted(dic.keys()):
print (key)
遍历字典中所有键
要用到values()
for value in dic.values():
print (value)
为剔除重复项,可使用set()
for value in set(dic.values()):
print (value)
嵌套
字典列表
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]
# 创建一个用于存储外星人的空列表
aliens = []
# 创建30个绿色的外星人
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)))
在字典中存储列表
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
在字典中存储列表字典
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
编写一个循环,提示用户输入一系列的比萨配料,并在用户输入 'quit'时结束循环。每当用户输入一种配料后,都打印一条消息,说我们会在比萨中添 加这种配料
peiliao = " "
while peiliao != "quit":
peiliao = input("请输入您想要的比萨配料(输入quit结束):\n")
print("我们会在比萨中添加" + peiliao + ".\n")