编写程序,将下面的数据存入字典,分别逐行遍历输出键、值和键值对。 遍历字典的键 name: tom age:20 sex:male 【提示】用keys()、values()和items()
时间: 2023-03-28 22:02:18 浏览: 43
以下是我的回答:
键:
name
age
sex
值:
tom
20
male
键值对:
name: tom
age: 20
sex: male
代码如下:
data = {"name": "tom", "age": 20, "sex": "male"}
# 遍历键
for key in data.keys():
print(key)
# 遍历值
for value in data.values():
print(value)
# 遍历键值对
for key, value in data.items():
print(key + ": " + str(value))
相关问题
编写程序,将下面的数据存入字典,分别逐行遍历输出键、值和键值对。
好的,这个问题我可以回答。以下是代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *data[] = {"name:Tom", "age:18", "gender:Male", "city:Beijing"};
int len = sizeof(data) / sizeof(char *);
char *key, *value;
char *token;
// 创建字典
char **dict = (char **)malloc(len * sizeof(char *));
for (int i = ; i < len; i++) {
dict[i] = (char *)malloc(50 * sizeof(char));
strcpy(dict[i], data[i]);
}
// 遍历字典
for (int i = ; i < len; i++) {
// 输出键
token = strtok(dict[i], ":");
key = token;
printf("键:%s\n", key);
// 输出值
token = strtok(NULL, ":");
value = token;
printf("值:%s\n", value);
// 输出键值对
printf("键值对:%s:%s\n", key, value);
}
// 释放内存
for (int i = ; i < len; i++) {
free(dict[i]);
}
free(dict);
return ;
}
```
输出结果如下:
```
键:name
值:Tom
键值对:name:Tom
键:age
值:18
键值对:age:18
键:gender
值:Male
键值对:gender:Male
键:city
值:Beijing
键值对:city:Beijing
```
阅读全文