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

如何使用while循环遍历字典(dictionary)中的全部键值对?

实现方法

这种需求是完全可行的。
因为while循环需要通过索引偏移来迭代元素,所以首先要把字典的items()视图转换成可以按下标访问的列表,之后通过维护索引变量完成遍历即可。
另外你提供的for循环存在一个小细节问题:dict.items()返回的是(键, 值)格式的元组,你写的for values,keys in user_info.items()变量名写反了,调整后更符合常规使用习惯。

while循环实现代码

user_info = {
    "username" : "Hansana123",
    "password" : "1234",
    "user_id" : 3456,
    "reg_date" : "Nov 19"
}

# 将字典items转为可按索引访问的列表
items_list = list(user_info.items())
index = 0
while index < len(items_list):
    key, value = items_list[index]
    print(key, "=", value)
    index += 1

补充说明

实际开发场景中遍历字典优先使用for循环即可,写法更简洁,也不需要额外维护索引变量。while遍历字典的写法仅适合有特殊步进、中断逻辑的定制化遍历场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 04:06:01