-1

I am facing issue. I have two lists where one list contains keys say ['a','a','a','b','b','b','b'] but the list was in ['a','b','a','b','a','b'] this form converted into above list by using sorted() and another list contains values say ['1','2','3','4','5','6']. I want to make dictionary using the two lists, How can I do that? I have tried Zip method though it is returing only the last values

My code:

input:lst =  ['a','b','a','b','a','b']
lst2 = sorted(lst)
score =[1,2,3,4,5,6]
dictionary = dict(zip(lst2, score))
Output:
{'a':3,'b':6}

What I want is

    input:
    lst =  ['a','b','a','b','a','b']
    lst2 = sorted(lst)
    score =[1,2,3,4,5,6]
    excepted output :
{'a':1,'a':2,'a':3,'b':4,'b':5,'b':6}
Ram dr
  • 111
  • 5
  • 1
    Unfortunately you can't. Dictionaries in python can only have unique keys. What are you trying to accomplish with your dictionary? – goalie1998 Jan 22 '21 at 05:15
  • 1
    Does this answer your question? [Make a dictionary with duplicate keys in Python](https://stackoverflow.com/questions/10664856/make-a-dictionary-with-duplicate-keys-in-python) – Mateo Torres Jan 22 '21 at 05:15
  • 1
    The "expected output" would pose a problem: what would be returned if you called `dictionary['a']`? Would it return 1, 2, or 3? – knosmos Jan 22 '21 at 05:18
  • @knosmos it would give the last value that's 3. – Ram dr Jan 22 '21 at 05:39
  • @goalie1998 I have accuracy scores for 2 ml algos with 3 different data. I wanted create a dict which shows the score for the 2 model with respctive to the 3 diff data which is passed into the model. Like, d ={Dt:0.89,Dt:0.90,Dt:0.91,lr:0.89.......} – Ram dr Jan 22 '21 at 05:45
  • @torresmateo that's helpful though I am getting a wrong output – Ram dr Jan 22 '21 at 05:46
  • Can you edit your post to show what you tried and what the output was for when you used defaultdict? – goalie1998 Jan 22 '21 at 05:48
  • Thanks for your time. I have turned the elements to be unique something like dt_sampledata[1]..... – Ram dr Jan 22 '21 at 05:53
  • @Ramdr - any feedback would be appreciated! Thanks – Dev Jan 24 '21 at 11:18

1 Answers1

1

In Python Dictionary, your keys must be unique - therefore can't have duplicates as others have already mentioned.

I believe the Collections module in Python can help you group the data.

lst = ['a','b','a','b','a','b']
lst.sort() # in-place sort
score = [1,2,3,4,5,6]

from collections import defaultdict
output_list = defaultdict(list)
for A, B in zip(lst, score):
    output_list[A].append(B)

output_list yields:

defaultdict(list, {'a': [1, 2, 3], 'b': [4, 5, 6]})
Dev
  • 665
  • 1
  • 4
  • 12