Make a dictionary with duplicate keys in Python

后端 未结 7 1074
野的像风
野的像风 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.

    0 讨论(0)
提交回复
热议问题