Reputation: 77
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?
Upvotes: 0
Views: 77
Reputation: 190
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
Create and dict with all keys of L1 and an empty list in value
Add the value of L2 (know the key by the index on enumerate)
Upvotes: 0
Reputation: 4981
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)
As @KellyBundy suggests, you could use this more pythonic
way to solve it too:
dc = defaultdict(list)
for item, plate in zip(L1, L2):
dc[item].append(plate)
pprint(dc)
Upvotes: 2
Reputation: 5005
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']}
Upvotes: 0
Reputation: 800
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
Upvotes: 1