Python中如何将字典的每个键值对作为参数传入其他函数
实现方案
你可以直接遍历字典的items()方法获取每一组键值对,逐次调用set_detail_to_user函数即可,修改后的调用代码如下:
# 处理用户ID user = new.__id.replace('-', '') # 获取属性字典 my_dict = new.__dict__ # 遍历字典所有键值对逐次调用设置函数 for key, value in my_dict.items(): set_detail_to_user(user, key, value)
注意事项
- 如果
new.__dict__里包含不需要设置的内置属性(比如Python对象自带的_开头的私有属性等),可以加过滤逻辑跳过无效键,示例如下:
for key, value in my_dict.items(): # 跳过私有属性,只处理公开字段,可按需调整过滤规则 if not key.startswith('_'): set_detail_to_user(user, key, value)
- 若担心单次调用失败影响后续字段设置,可以加异常捕获逻辑:
for key, value in my_dict.items(): if not key.startswith('_'): try: set_detail_to_user(user, key, value) except Exception as e: print(f"设置用户字段{key}失败:{str(e)}")
内容的提问来源于stack exchange,提问作者Aymen haddaji
相关产品推荐
相关产品推荐

