Tamil
Tamil

Reputation: 1203

Merge multiple list into single dictionary in python

I am trying to merge the following list to dictionary as follow:

resultant_dict = {}
key = [101, 102, 103]
values1 = [1,2,3]
values2 = [4,5,6]
values3 = [7,8,9]

the output should be:

output = {101: '147', 102: '258', 103: '369'}

Values being concatenate with each other. Is there an efficient way to do this?

Thanks in advance!!

Upvotes: 1

Views: 430

Answers (2)

Chanda Korat
Chanda Korat

Reputation: 2561

Try this,

resultant_dict = {}
key = [101, 102, 103]
values1 = [1,2,3]
values2 = [4,5,6]
values3 = [7,8,9]

for i in range(len(key)):
    resultant_dict[key[i]]=str(values1[i])+str(values2[i])+str(values3[i])

print resultant_dict

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476534

It is rather weird that the values in the resulting dictionary should be strings, but if that is what you want, you can use zip and join in a single dictionary comprehension:

output = {k:''.join(str(x) for x in xs) for k,*xs in zip(key,values1,values2,values3)}

in , or for :

output = {k:''.join(str(x) for x in xs) for k,xs in zip(key,zip(values1,values2,values3))}

By using zip(key,values1,values2,values3) we create an iterable that will generate tuples of the form:

(101,1,4,7),(102,2,5,8),...

Now we use for k,*xs to unify k with the first element of every tuple, and the remaining elements are stored in xs (so xs is (1,4,7) for the first tuple).

Now we use ''.join(str(x) for x in xs) to convert all the elements in xs to strings and we join these together.

Finally we have k:''.join(str(x) for x in xs) which is dictionary comprehension syntax.

Upvotes: 4

Related Questions