创建字典stu_1,使属性与内容形成对应关系如下: name:Tom,age:18,number:20200876,score:486 (1)为字典stu_1添加新的元素:address:北京 (2)遍历字典stu_1的键、遍历字典stu_1的值、遍历字典stu_1的元素。
时间: 2024-03-27 19:35:40 浏览: 78
好的,按照您的要求,我来给您展示如何操作:
```python
# 创建字典stu_1
stu_1 = {'name': 'Tom', 'age': 18, 'number': 20200876, 'score': 486}
# 添加新元素
stu_1['address'] = '北京'
# 遍历字典stu_1的键
print("字典stu_1的键为:")
for key in stu_1.keys():
print(key)
# 遍历字典stu_1的值
print("字典stu_1的值为:")
for value in stu_1.values():
print(value)
# 遍历字典stu_1的元素
print("字典stu_1的元素为:")
for item in stu_1.items():
print(item)
```
输出结果如下:
```
字典stu_1的键为:
name
age
number
score
address
字典stu_1的值为:
Tom
18
20200876
486
北京
字典stu_1的元素为:
('name', 'Tom')
('age', 18)
('number', 20200876)
('score', 486)
('address', '北京')
```
相关问题
创建字典stu_1,使属性与内容形成对应关系如下: name:Tom,age:18,number:20200876,score:486 (1)为字典stu_1添加新的元素:address:北京 (2)遍历字典stu_1的键、遍历字典stu_1的值、遍历字典stu_1的元素
好的,您可以像这样创建一个属性与内容对应的字典stu_1:
```python
stu_1 = {"name": "Tom", "age": 18, "number": 20200876, "score": 486}
```
要为字典stu_1添加新的元素address,可以直接使用赋值操作符:
```python
stu_1["address"] = "北京"
```
要遍历字典stu_1的键,可以使用keys()方法:
```python
for key in stu_1.keys():
print(key)
```
要遍历字典stu_1的值,可以使用values()方法:
```python
for value in stu_1.values():
print(value)
```
要遍历字典stu_1的元素,可以使用items()方法:
```python
for item in stu_1.items():
print(item)
```
需要注意的是,items()方法返回的是一个由键值对组成的元组,可以使用多个变量来接收元组中的键和值:
```python
for key, value in stu_1.items():
print(key, value)
```
希望这个回答对您有所帮助!
创建字典stu_1,使属性与内容形成对应关系如下: #name:Tom,age:18,number:20200876,score:486 #(1)为字典stu_1添加新的元素:address:北京 #(2)遍历字典stu_1的键、遍历字典stu_1的值、遍历字典stu_1的元素。
下面是实现你所需求的Python代码:
```python
# 创建字典stu_1
stu_1 = {"name": "Tom", "age": 18, "number": 20200876, "score": 486}
# 添加新元素
stu_1["address"] = "北京"
# 遍历键
print("遍历字典stu_1的键:")
for key in stu_1.keys():
print(key)
# 遍历值
print("遍历字典stu_1的值:")
for value in stu_1.values():
print(value)
# 遍历元素
print("遍历字典stu_1的元素:")
for item in stu_1.items():
print(item)
```
输出结果如下:
```
遍历字典stu_1的键:
name
age
number
score
address
遍历字典stu_1的值:
Tom
18
20200876
486
北京
遍历字典stu_1的元素:
('name', 'Tom')
('age', 18)
('number', 20200876)
('score', 486)
('address', '北京')
```
阅读全文