Reputation: 63
I am trying to merge two lists with different lengths to dictionary. Pls help
listA = ['2','4','6','8','10','12','14','16','18','20','22','24','26','28']
listB = ['host1','host2','host3','host4']
expected output:
{
host1: [2,10,18,26],
host2: [4,12,20,28],
host3: [6,14,22],
host4 : [8,16,24]
}
Upvotes: 0
Views: 44
Reputation: 106455
You can use the following dict constructor with a zip of the keys and a list of sliced sub-lists:
print(dict(zip(listB, [listA[i::len(listB)] for i in range(len(listB))])))
This outputs:
{'host1': ['2', '10', '18', '26'], 'host2': ['4', '12', '20', '28'], 'host3': ['6', '14', '22'], 'host4': ['8', '16', '24']}
Upvotes: 1
Reputation: 24691
It looks like you want to have a dictionary where every fourth element in listA
is a member of listB
. You can do this using python's list slicing, and using a generator function:
s = len(listB)
output = {listB[i]: listA[i::s] for i in range(s)}
This should be fairly straightforward. The fancy list slicing thing is listA[i::s]
, which takes every s
th element of listA
, starting from the i
th element.
Upvotes: 3