Python for Developers 入门
Jasmin Ludolf
Senior Data Science Content Developer
ingredients = ["pasta", "tomatoes", "garlic", "basil", "olive oil", "salt"]# 配料用量(克) quantities = [500, 400, 15, 20, 30, 5]

usernameemailpreferences
ip_addresslocation$$


# 创建字典
recipe =
# 创建字典
recipe = {
# 创建字典
recipe = {"pasta"
# 创建字典
recipe = {"pasta":
# 创建字典
recipe = {"pasta": 500
# 创建字典
recipe = {"pasta": 500,
# 创建字典
recipe = {"pasta": 500,
"tomatoes": 400,
# 创建字典
recipe = {"pasta": 500,
"tomatoes": 400,
"garlic": 15,
"basil": 20,
"olive oil": 30,
"salt": 5
# 创建字典
recipe = {"pasta": 500,
"tomatoes": 400,
"garlic": 15,
"basil": 20,
"olive oil": 30,
"salt": 5}
字典是有序的
需要多少意面?
# 查找配料用量
print(recipe["pasta"])
500
# 获取字典的所有值
print(recipe.values())
dict_values([500, 400, 15, 20, 30, 5])
# 获取字典的所有键
print(recipe.keys())
dict_keys(['pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'])
# 打印字典
print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5}
# 获取所有项(键-值对)
print(recipe.items())
dict_items([('pasta', 500), ('tomatoes', 400), ('garlic', 15), ('basil', 20),
('olive oil', 30), ('salt', 5)])
# 添加新的键-值对
recipe["parmesan"] = 50
print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
print(recipe)
{'pasta': 500, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
# 更新已有键对应的值
recipe["pasta"] = 1000
print(recipe)
{'pasta': 1000, 'tomatoes': 400, 'garlic': 15, 'basil': 20, 'olive oil': 30,
'salt': 5, 'parmesan': 50}
# 创建含重复键的字典 recipe = {"pasta": 500, "garlic": 5, "garlic": 15, "basil": 20, "olive oil": 30, "salt": 5}# 打印重复键的值 print(recipe["garlic"])
15
Python for Developers 入门