Creating a dictionary from 2 lists with duplicate keys

前端 未结 2 1918
醉梦人生
醉梦人生 2020-12-18 14:12

Though I have seen versions of my issue whereby a dictionary was created from two lists (one list with the keys, and the other with the corresponding values), I want to crea

相关标签:
2条回答
  • 2020-12-18 14:45

    As already mentioned, your desired output is not possible as dictionary keys must be unique.

    Below are 2 alternatives if you do not want to lose data.

    List of tuples

    res = [(i, j) for i, j in zip(keys, values)]
    
    # [(18, [7, 8, 9]),
    #  (34, [4, 5, 6]),
    #  (30, [1, 2, 3]),
    #  (30, [10, 11, 12]),
    #  (18, [13, 14, 15])]
    

    Dictionary of lists

    from collections import defaultdict
    
    res = defaultdict(list)
    
    for i, j in zip(keys, values):
        res[i].append(j)
    
    # defaultdict(list,
    #             {18: [[7, 8, 9], [13, 14, 15]],
    #              30: [[1, 2, 3], [10, 11, 12]],
    #              34: [[4, 5, 6]]})
    
    0 讨论(0)
  • 2020-12-18 14:58
    Keys need to be unique. 
    You Have keys = [18, 34, 30, 30, 18]
    Repeated keys 18 and 30 can not be used twice.
    Try your script with unique keys and it works fine.
    Keys read right to left. Notice you get the first key 18 
    and the first key 30, but the second of each key is passed over 
    
    0 讨论(0)
提交回复
热议问题