Reputation: 1203
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
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
Reputation: 476534
It is rather weird that the values in the resulting dictionary should be str
ings, 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 python-3.x, or for python-2.7:
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