利用Python根据下面提示建一个字典结构,并访问遍历它。 pizza字典包括:大小是中等尺寸的的,口味是奶酪味的,类型是美式的,数量是2个,运输方式是送货上门,地址是济南大学你们宿舍.... 自己发挥并构造字典吧! 要求: 练习访问字典pizza中的元素: (1)输出字典pizza (2)使用键输出值; (3)使用for语句遍历; (4)使用get方法访问 (5)访问并输出所有键值对、所有键、所有值 (6)添加价格为39进pizza
时间: 2023-06-02 15:08:09 浏览: 62
好的,我已经明白您的要求了。下面是Python代码实现:
```python
# 利用Python创建一个字典结构
pizza = {
"size": "medium",
"flavor": "cheese",
"type": "American",
"quantity": 2,
"delivery": "home delivery",
"address": "the dormitory of Jinan University"
}
# 输出整个字典
print("The contents of the pizza dictionary are:")
print(pizza)
# 使用键输出值
print("The value of the 'size' key is:", pizza["size"])
print("The value of the 'flavor' key is:", pizza["flavor"])
print("The value of the 'type' key is:", pizza["type"])
print("The value of the 'quantity' key is:", pizza["quantity"])
print("The value of the 'delivery' key is:", pizza["delivery"])
print("The value of the 'address' key is:", pizza["address"])
# 使用for语句遍历
print("All key-value pairs in the pizza dictionary are:")
for key, value in pizza.items():
print(key, ":", value)
# 使用get方法访问
print("The value of the 'flavor' key is:", pizza.get("flavor"))
# 访问并输出所有键值对、所有键、所有值
print("All key-value pairs in the pizza dictionary are:")
for item in pizza.items():
print(item)
print("All keys in the pizza dictionary are:")
for key in pizza.keys():
print(key)
print("All values in the pizza dictionary are:")
for value in pizza.values():
print(value)
# 添加价格为39进pizza
pizza["price"] = 39
print("The contents of the updated pizza dictionary are:")
print(pizza)
```
运行结果如下:
```
The contents of the pizza dictionary are:
{'size': 'medium', 'flavor': 'cheese', 'type': 'American', 'quantity': 2, 'delivery': 'home delivery', 'address': 'the dormitory of Jinan University'}
The value of the 'size' key is: medium
The value of the 'flavor' key is: cheese
The value of the 'type' key is: American
The value of the 'quantity' key is: 2
The value of the 'delivery' key is: home delivery
The value of the 'address' key is: the dormitory of Jinan University
All key-value pairs in the pizza dictionary are:
size : medium
flavor : cheese
type : American
quantity : 2
delivery : home delivery
address : the dormitory of Jinan University
The value of the 'flavor' key is: cheese
All key-value pairs in the pizza dictionary are:
('size', 'medium')
('flavor', 'cheese')
('type', 'American')
('quantity', 2)
('delivery', 'home delivery')
('address', 'the dormitory of Jinan University')
All keys in the pizza dictionary are:
size
flavor
type
quantity
delivery
address
All values in the pizza dictionary are:
medium
cheese
American
2
home delivery
the dormitory of Jinan University
The contents of the updated pizza dictionary are:
{'size': 'medium', 'flavor': 'cheese', 'type': 'American', 'quantity': 2, 'delivery': 'home delivery', 'address': 'the dormitory of Jinan University', 'price': 39}
```
希望我的回答能够帮助到您。如果您还有其他问题或需求,欢迎随时提出。
阅读全文