0

this might be a naive question, I have two lists, say list1 and list2.

list1 =[[('a', 'b'), ('c', 'd')], [('e', 'f'), ('g', 'h')]]
list2 =['aa', 'aa']

When I do

dict(zip(list2, list1)) 

I get the following

{'aa': [('e', 'f'), ('g', 'h')]}

The output I want is

{'aa': [('a', 'b'), ('c', 'd')], 'aa': [('e', 'f'), ('g', 'h')]}

When I change list2 to:

list2 = ['aa1', 'aa2']
dict(zip(list2, list1))

gives

{'aa1': [('a', 'b'), ('c', 'd')], 'aa2': [('e', 'f'), ('g', 'h')]}

Why I am not getting desired output in the first case? Could you please help me on this. Thanks in advance.

cs95
  • 379,657
  • 97
  • 704
  • 746
hemanta
  • 1,405
  • 2
  • 13
  • 23
  • 4
    Please explain why you think this is a good idea, and what `result['aa']` should return if you have two identical keys? – cs95 Jan 19 '19 at 21:34
  • 6
    You simply cannot have two identical keys in a dictionary, that's not how it works. – Óscar López Jan 19 '19 at 21:37
  • I understood that, when we say dict(zip(B, A)), the original value in key 'aa' is replaced with the new one, which get printed. – hemanta Jan 19 '19 at 21:58
  • 1
    A dictionary is a hash table. With hash tables, you can only have unique keys. You could use a different data structure if you want to not have unique keys. For example, you could use a tuple: `tuple(zip(list2, list1))`. Or you could use `collections.defaultdict` to append values onto an existing key if you still wanted to use a dictionary structure (and have constant lookup time). – Joe Patten Jan 19 '19 at 22:02

1 Answers1

0

By default dict in python cannot have duplicate key, in the other hand we can have multiple values. In the first statement, python will add the key aa with the value :

[('a', 'b'), ('c', 'd')]

then it will overwrite its value with :

 [('e', 'f'), ('g', 'h')]

To create dict with duplicate keys, take a look at this make dictionary with duplicate keys in python