网站首页 > 技术文章 正文
1、编程试题:
作为值的嵌套字典指的是一个字典作为另一个字典中键的值存储。例如:
employee = {
"name": "John Doe",
"contact": {
"email": "johndoe@example.com",
}
}
在这里,字典{"email": "johndoe@example.com",}是employee字典中"contact"键的值。
编写一个程序,将整数列表的每个元素与字典的每个项映射,形成一个嵌套字典。
定义函数map_list_dict(),它有两个参数input_dict和input_list。
在函数内部,将列表的每个元素映射到字典的相应键值对
形成一个新的字典,列表元素作为键,嵌套字典(包含输入字典的单个键值对)作为值并打印。
示例输入
{"a": 1, "b": 2, "c": 3}
6 7 8
示例输出
{6: {'a': 1}, 7: {'b': 2}, 8: {'c': 3}}
2、代码实现:

可编辑代码如下:
#!/usr/bin/python3.9
# -*- coding: utf-8 -*-
#
# Copyright (C) 2024 , Inc. All Rights Reserved
#
# @Time : 2024/2/8 19:48
# @Author : fangel
# @FileName : 101. 从列表创建嵌套字典.py
# @Software : PyCharm
# 使用json模块解析输入并处理JSON数据
import json
def map_list_dict(input_dict, input_list):
resDict = {}
for item in input_list:
tmpDict = {}
#先根据索引(即也是for循环的次数)获取输入的字典中的键和值
oldkey = list(input_dict.keys())[input_list.index(item)]
oldvalue = input_dict[oldkey]
#将获取到的键和值重新组成一个临时的字典
tmpDict[oldkey] = oldvalue
#将这个字典做为新的值(键即是列表中的值)
resDict[item] = tmpDict
return resDict
# 获取输入字符串并将其解析为json
input_dict = json.loads(input())
# 获取整数输入并将其转换为列表
input_list = list(map(int, input().split()))
# 调用函数
print(map_list_dict(input_dict, input_list))
3、代码分析:
详见代码注释部分,先获取输入字典中的键和值,然后组成一个临时的字典,再将该字典做为新的值;
4、运行结果:
输入:
{"Name":"Tina","Roll":12}
5 6
输出:
{5: {'Name': 'Tina'}, 6: {'Roll': 12}}
猜你喜欢
- 2024-12-30 在 Python 中使用 f-String 格式化字符串
- 2024-12-30 CSnakes:在.NET项目中嵌入Python代码的工具
- 2024-12-30 10个小技巧,让你的 Python 代码更加优雅
- 2024-12-30 什么是Python中的DSL领域特定语言?
- 2024-12-30 python笔记:for循环嵌套。end=""的作用,图形打印
- 2024-12-30 PyScript:让Python在HTML中运行(python处理html文件)
- 2024-12-30 PythonNet:实现Python与.Net代码相互调用!
- 2024-12-30 Python嵌入版(python嵌入版区别)
- 2024-12-30 Python教程-嵌套字典(python字典嵌套字典取值)
- 2024-12-30 Python短文,Python中的嵌套条件语句(六)
- 05-25Python 3.14 t-string 要来了,它与 f-string 有何不同?
- 05-25Python基础元素语法总结
- 05-25Python中的变量是什么东西?
- 05-25新手常见的python报错及解决方案
- 05-2511-Python变量
- 05-2510个每个人都是需要知道Python问题
- 05-25Python编程:轻松掌握函数定义、类型及其参数传递方式
- 05-25Python基础语法
- 257℃Python短文,Python中的嵌套条件语句(六)
- 257℃python笔记:for循环嵌套。end=""的作用,图形打印
- 256℃PythonNet:实现Python与.Net代码相互调用!
- 251℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 251℃Python实现字符串小写转大写并写入文件
- 106℃原来2025是完美的平方年,一起探索六种平方的算吧
- 90℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 81℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)