如何遍历字典的键及对应列表值,打印键与对应列表的每个元素
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
相关产品推荐
相关产品推荐

