daydreamer
daydreamer

Reputation: 91959

what is the most efficient way to creating a dict with two lists?

I have two lists like

x = ['a', 'b', 'c', 'd'] and
y = [1, 2, 3, 4] 

I have to create a dict from these two lists so that result is

{
 'a': 1,
 'b': 2,
 'c': 3,
 'd': 4
}

I do it using the following

dict(zip(x, y))  

Is there a better and fast/efficient way of doing it?
I have to perform this operation on [m, b]illion of times and on different lists

Thank you

Upvotes: 0

Views: 205

Answers (1)

Ricardo Altamirano
Ricardo Altamirano

Reputation: 15198

Per Praveen Gollakota's comment, the original method will work fine. In Python 2.x, you can also use the izip function in the itertools module. Either of these methods will work:

import itertools

x = ['a', 'b', 'c', 'd']
y = [1, 2, 3, 4]

method1 = dict(zip(x, y))
method2 = itertools.izip(x, y)

In Python 3.x, zip returns an iterator by default, so this method will work perfectly:

x = ['a', 'b', 'c', 'd']
y = [1, 2, 3, 4]

method1 = dict(zip(x, y))

Upvotes: 2

Related Questions