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

如何遍历字典的键及对应列表值,打印键与对应列表的每个元素

Python实现字典键与对应列表元素逐一配对打印

实现思路

用两层嵌套for循环即可完成需求:

  • 外层循环遍历字典的键值对,拿到每个键和其对应的列表
  • 内层循环遍历该列表的所有元素,将键和当前元素配对打印即可

完整可运行代码

def pair_and_print(input_dict):
    for key, item_list in input_dict.items():
        for item in item_list:
            print(f"{key} {item}")

# 测试用例
dictionary = {"red":["apple","shirt","firetruck"], "blue":["sky","ocean"]}
pair_and_print(dictionary)

输出结果

运行上述代码后,输出完全符合要求:

red apple
red shirt
red firetruck
blue sky
blue ocean

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 20:36:02