R. Leal
R. Leal

Reputation: 71

Create a dictionary from a two dimensional list in Python

i'm facing some troubles to create a dictionary from a list and a list of lists. Here's an example:

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

I want a output using the elements of list a and the third element of list b, like this output:

a = {'a': 0, 'b': 1, 'c': 0, 'd': 1]

Both lists have the same length, so i tried something like:

c = dict(zip(a,b))

But in this case, i can't select the third element of b.

In my real case, i have millions of data, so i need a fast and simple way to do it, and create a temporary list from b may not be a optimal solution.

Thanks

Upvotes: 0

Views: 414

Answers (4)

Sunny Patel
Sunny Patel

Reputation: 8077

You can make use of itemgetter inside the operator module. Where 2 represents the index within the b sublists.

from operator import itemgetter
a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(zip(a, map(itemgetter(2), b)))

and since you have lots of elements, maybe itertools will help with memory:

from operator import itemgetter
from itertools import izip, imap

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = dict(izip(a, imap(itemgetter(2), b)))

These solutions will help take advantage of the underlying C modules for performance benefits.

Upvotes: 0

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22997

Or, using a dictionary in comprehension:

a = ['a','b','c','d']
b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]

c = {k: v[-1] for k, v in zip(a, b)}

See PEP274 Dict Comprehensions

Upvotes: 1

Pedro Rodrigues
Pedro Rodrigues

Reputation: 424

I've tried this one and it seemed to have worked:

>>> a = ['a','b','c','d']
>>> b = [[1,2,0], [3,4,1], [5,6,0], [7,8,1]]
>>> c = dict(zip(a, [d[2] for d in b]))
>>> c
{'a': 0, 'c': 0, 'b': 1, 'd': 1}

Upvotes: 0

mgilson
mgilson

Reputation: 310307

You could do:

dict(zip(a, (x[-1] for x in b)))  # Maybe x[2] if some of the sublists have more than 3 elements.

If you are on python2.x, you might want to use itertools.izip or future_builtins.zip

Upvotes: 2

Related Questions