user9599919
user9599919

Reputation: 63

merge 2 different lists to dictionary

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

Answers (2)

blhsing
blhsing

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

Green Cloak Guy
Green Cloak Guy

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 sth element of listA, starting from the ith element.

Upvotes: 3

Related Questions