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]
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})