Merging two lists into dictionary while keeping duplicate data in python

后端 未结 8 2130
北海茫月
北海茫月 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:35

    You have two options :

    either you use tuple :

    list_one = ['a', 'a', 'c', 'd']
    
    list_two = [1,2,3,4]
    
    
    
    print(list(map(lambda x,y:(x,y),list_one,list_two)))
    

    output:

    [('a', 1), ('a', 2), ('c', 3), ('d', 4)]
    

    Second option is use this pattern:

    dict_1={}
    
    for key,value in zip(list_one,list_two):
        if key not in dict_1:
            dict_1[key]=[value]
        else:
            dict_1[key].append(value)
    
    print(dict_1)
    

    output:

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

提交回复
热议问题