Home > Software design >  Iterating 2 lists to form a dictionary with unique key but multiple items
Iterating 2 lists to form a dictionary with unique key but multiple items

Time:06-12

I've got 2 lists, one with plate numbers that has duplicates in it, and the other with corresponding groups that each plate belongs to. Duplicated number means that the plate belongs to several groups. I'm trying to make a dict with the following output:

L1 = ['173', '607', '607', '581', '522', '522']
L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']

# Desirable output
# '173': 'fleet 6'
# '607': ['fleet4', 'fleet6']
# '581': 'Toyota'
# '522': ['Maintenance', 'fleet 1'] 

I have no clue how to cluster values as lists from L2 to match with duplicates from L1, along with singles, any ideas please?

CodePudding user response:

Try this approach to see if that help. It's only one way to solve it, prob. easy to understand.

from collections import defaultdict
from pprint import pprint

L1 = ['173', '607', '607', '581', '522', '522']

L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']

# Desirable output
# '173': 'fleet 6'
# '607': ['fleet4', 'fleet6']
# '581': 'Toyota'
# '522': ['Maintenance', 'fleet 1']

dc = defaultdict(list)

for i in range(len(L1)):
    item = L1[i]
    dc[item].append(L2[i])

pprint(dc)

CodePudding user response:

Try the following:

d = {}

L1 = ['173', '607', '607', '581', '522', '522']
L2 = ['fleet 6', 'fleet 4', 'fleet 6', 'Toyota', 'Maintenance', 'fleet 1']

for l1, l2 in zip(L1, L2):
   d[l1] = d.get(l1, [])
   d[l1].append(l2)

Where the d.get() function gets the item and if the key does not exist returns an empty list

CodePudding user response:

You can make this:

result = {key: [] for key in L1}

for i, value in enumerate(L2):
    result[L1[i]].append(value)

Simple and quick!

Steps

  1. Create and dict with all keys of L1 and an empty list in value

  2. Add the value of L2 (know the key by the index on enumerate)

CodePudding user response:

Using setdefault:

d = {}

for k, v in zip(L1, L2):
    d.setdefault(k, []).append(v)

print(d)
#{'173': ['fleet 6'], '607': ['fleet 4', 'fleet 6'], '581': ['Toyota'], '522': ['Maintenance', 'fleet 1']}
  • Related