Merging two lists into dictionary while keeping duplicate data in python

后端 未结 8 2089
北海茫月
北海茫月 2021-01-17 09:09

Hi, I want to merge two lists into one dictionary. Suppose I have two lists such as below

list_one = [\'a\', \'a\', \'c\', \'d\']

list_two = [1,2,3,4]

8条回答
  •  天命终不由人
    2021-01-17 09:46

    Since keys in dictionaries are unique, getting {'a': 1, 'a': 2, 'c': 3, 'd': 4} is impossible here for regular python dictionaries, since the key 'a' can only occur once. You can however have a key mapped to multiple values stored in a list, such as {'a': [1, 2], 'c': [3], 'd': [4]}.

    One option is to create a defaultdict to do this easily for you:

    from collections import defaultdict
    
    list_one = ['a', 'a', 'c', 'd']
    
    list_two = [1, 2, 3, 4]
    
    d = defaultdict(list)
    for key, value in zip(list_one, list_two):
        d[key].append(value)
    
    print(dict(d))
    

    Which outputs:

    {'a': [1, 2], 'c': [3], 'd': [4]}
    

提交回复
热议问题