Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a dictionary from 2 lists by storing multiple values with repeated keys

There are 2 lists. What I am trying to do is to find the occurrence of first list elements and will hold the values of second list for a key in first list and in the end, it will become dictionary holding specific keys from list 1 and values from list 2

Input:

list1 = ['A', 'A', 'B', 'B', 'C', 'D']
list2 = [1, 2, 3, 4, 5, 6]

Expected Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D':[6]}

Current Output:

{'A': [1, 2], 'B': [4], 'C': []}

What I tried so far,

values = [list2[0]]
key = list1[0]
dic = {}
for i in range(1, len(list1)):
    if list1[i] == list1[i - 1]:
        values.append(list2[i])
    elif list1[i] != list1[i - 1]:
        dic.update({key: values})
        values = []
        key = list1[i]
print(dic)

List 1 and List 2 are always equal in length and sorted

>Solution :

You can use dict.setdefault to initialize each distinct key with a new list to append values to:

output = {}
for key, value in zip(list1, list2):
    output.setdefault(key, []).append(value)

output would become:

{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D': [6]}

Demo: https://replit.com/@blhsing/InstructiveNoxiousCollaborativesoftware

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading