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']})