Merging two lists into dictionary while keeping duplicate data in python

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

    Dictionaries must have unique keys, so you would have to change your requirement. How about a list of tuples as a workaround?

    l = list(zip(['a', 'a', 'c', 'd'],[1,2,3,4]))
    print(l)
    

    With the resulting being:

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

    You can easily iterate over and unpack like so:

    for k, v in l:
        print("%s: %s" % (k, v))
    

    which produces:

    a: 1
    a: 2
    c: 3
    d: 4
    

    If you want it hashable, you can create a tuple of tuples like so:

    l = tuple(zip(['a', 'a', 'c', 'd'],[1,2,3,4]))
    

提交回复
热议问题