Make a dictionary with duplicate keys in Python

后端 未结 7 1080
野的像风
野的像风 2020-11-22 00:37

I have the following list which contains duplicate car registration numbers with different values. I want to convert it into a dictionary which accepts this multiple keys of

7条回答
  •  无人及你
    2020-11-22 01:16

    Python dictionaries don't support duplicate keys. One way around is to store lists or sets inside the dictionary.

    One easy way to achieve this is by using defaultdict:

    from collections import defaultdict
    
    data_dict = defaultdict(list)
    

    All you have to do is replace

    data_dict[regNumber] = details
    

    with

    data_dict[regNumber].append(details)
    

    and you'll get a dictionary of lists.

提交回复
热议问题