You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用**kwargs返回字典的输出顺序与预期不符问题咨询

问题原因
  • 首先修正代码笔误:函数定义的形参**user info中间存在多余空格,需改为**user_info,否则代码运行会直接报语法错误。
  • 顺序不符合预期的核心逻辑:Python 3.7及以上版本中,普通字典会严格保留键的插入顺序。你的现有代码会先将调用时传入的location、field两个键值对插入到user_info字典中,之后才插入first_name、last_name键,所以输出顺序自然是额外参数在前、姓名字段在后。如果你使用的是Python 3.7以下版本,普通字典本身就不保证插入顺序,输出顺序随机属于正常特性。
解决方法

调整字典的插入顺序,优先插入姓名字段,再更新传入的自定义参数即可,修改后代码如下:

def build_profile(first, last, **user_info):
    # 初始化空字典,先插入姓名字段
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    # 再更新传入的其他自定义字段
    profile.update(user_info)
    return profile

user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)

运行后输出与你的预期完全一致:
{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}

如果需要兼容Python 3.7以下版本,可以使用collections.OrderedDict实现稳定保序:

from collections import OrderedDict

def build_profile(first, last, **user_info):
    profile = OrderedDict()
    profile['first_name'] = first
    profile['last_name'] = last
    profile.update(user_info)
    return profile

内容的提问来源于stack exchange,提问作者Neeraj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:27:04