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

Time:11-11

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:

{'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

CodePudding user response:

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

CodePudding user response:

There are multiple small issues with your code:

  1. you are missing the last entry in the dict, because the dict is only updated, if the value changes. However, for the last value (in your case 'D'), this is not the case.
  2. by initializing values with an empty list, you loose the first value

These issues could be fixed the following way:

  1. add dic.update({key: values}) below the loop
  2. change values = [] to values = [list2[i]]

CodePudding user response:

You can also use defaultdict from collections

from collections import defaultdict

list1 = ['A', 'A', 'B', 'B', 'C', 'D']

list2 = [1, 2, 3, 4, 5, 6]

d = defaultdict(list)
for key, value in zip(list1, list2):
    d[key].append(value)

print(dict(d))
{'A': [1, 2], 'B': [3, 4], 'C': [5], 'D': [6]}
  • Related