Python:嵌套字典缺失指定参数时插入当前年月值
问题描述
我有如下结构的Python字典:
'python_task': {'python_file': '/test_script.py', 'parameters': ['--first_param', 'One', '--second_param', 2]}
需要检查该字典的parameters列表中是否存在--year和--month,若不存在则添加当前年份和月份,最终字典结构如下:
'python_task': {'python_file': '/test_script.py', 'parameters': ['--first_param', 'One', '--second_param', 2, '--year', 2023, '--month', 8]}
我已有一个用于检查字典的函数:
from typing import Dict, Any def check_dict_key(item_dict: Dict[str, Any], key: str) -> bool: """ 检查给定字典中是否包含指定键,且对应值不为None。 :param item_dict: 待检查的字典 :type item_dict: Dict[str, Any] :param key: 待检查的键 :type key: str :return: 检查结果 :type: bool """ return bool(key in item_dict and item_dict[key] is not None)
但不清楚如何按示例中的顺序插入值,也不确定如何用datetime获取当前年月。我写的初始IF语句存在问题:
if not utils.check_dict_key(task_params, "--year"): task_params["parameters"]['--year'] task_params["parameters"]['']: date=datetime( year=task_params[parameters][''] )
希望得到相关帮助。
解决方案
1. 核心问题说明
你现有的check_dict_key函数是用来检查字典键的,但parameters是列表类型(不是字典),所以不能直接用这个函数判断--year/--month是否存在,需要针对列表结构重新写检查逻辑。
2. 分步实现
步骤1:获取当前年月
用datetime模块直接提取当前时间的年和月:
from datetime import datetime current_year = datetime.now().year current_month = datetime.now().month # 如果需要补零的月份字符串(比如"08"),可以用:current_month_str = f"{current_month:02d}"
步骤2:检查参数列表中是否存在目标选项
因为parameters是[选项名, 值, 选项名, 值]的结构,遍历列表的偶数索引(0、2、4...)即可判断是否存在目标选项:
def has_param(parameters: list, target_param: str) -> bool: """检查参数列表中是否存在指定选项""" for i in range(0, len(parameters), 2): if parameters[i] == target_param: return True return False
步骤3:添加缺失的参数
用extend()方法将缺失的选项和值追加到列表末尾,符合示例中的顺序要求:
# 假设原始字典存在变量task_dict中 task_dict = { 'python_task': { 'python_file': '/test_script.py', 'parameters': ['--first_param', 'One', '--second_param', 2] } } params = task_dict['python_task']['parameters'] # 检查并添加--year if not has_param(params, '--year'): params.extend(['--year', current_year]) # 检查并添加--month if not has_param(params, '--month'): params.extend(['--month', current_month])
3. 完整代码示例
from datetime import datetime from typing import Dict, Any def check_dict_key(item_dict: Dict[str, Any], key: str) -> bool: """ 检查给定字典中是否包含指定键,且对应值不为None。 :param item_dict: 待检查的字典 :type item_dict: Dict[str, Any] :param key: 待检查的键 :type key: str :return: 检查结果 :type: bool """ return bool(key in item_dict and item_dict[key] is not None) def has_param(parameters: list, target_param: str) -> bool: """检查参数列表中是否存在指定的选项""" for i in range(0, len(parameters), 2): if parameters[i] == target_param: return True return False if __name__ == "__main__": # 原始字典 task_dict = { 'python_task': { 'python_file': '/test_script.py', 'parameters': ['--first_param', 'One', '--second_param', 2] } } # 获取当前年月 current_year = datetime.now().year current_month = datetime.now().month # 处理参数列表 params = task_dict['python_task']['parameters'] if not has_param(params, '--year'): params.extend(['--year', current_year]) if not has_param(params, '--month'): params.extend(['--month', current_month]) # 输出结果 print(task_dict)
内容的提问来源于stack exchange,提问作者Prof. Falken
相关产品推荐
相关产品推荐

