python中,字典是一个key对应一个value,当我们需要一个key对应多个value,可采用collections模块的defaultdict来实现:
代码
from collections import defaultdict
dict_one_to_more = defaultdict(list)
for x in range(10)
dict_one_to_more["Key"].append("Value:" + str(x))
效果如下:
defaultdict(<class 'list'>, {'Key': ['Value:0', 'Value:1', 'Value:2', 'Value:3', 'Value:4', 'Value:5', 'Value:6', 'Value:7', 'Value:8', 'Value:9']})
本文介绍了如何在Python中使用字典实现一个键关联多个值的功能,通过示例代码展示了具体操作过程。
445





