Merging two lists into dictionary while keeping duplicate data in python

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

    As other answers have pointed out, dictionaries have unique keys, however, it is possible to create a structure to mimic the behavior you are looking for:

    class NewDict:
       def __init__(self, *values):
           self.values = list(zip(*values))
       def __getitem__(self, key):
            return [b for a, b in sorted(self.values, key=lambda x:x[0]) if a == key]
       def __repr__(self):
           return "{}({})".format(self.__class__.__name__, "{"+', '.join("{}:{}".format(*i) for i in sorted(self.values, key=lambda x:x[0]))+"}")
    
    list_one = ['a', 'a', 'c', 'd']
    list_two = [1,2,3,4]
    d = NewDict(list_one, list_two)
    print(d['a'])
    print(d)
    

    Output:

    [1, 2]
    NewDict({a:1, a:2, c:3, d:4})
    

提交回复
热议问题