Python 实现字典的一个Key(键)对应多个Value(值)

    技术2024-07-21  78

    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']})
    Processed: 0.017, SQL: 10