user3449833
user3449833

Reputation: 809

Convert 3-Element List of Tuples to Dictionary

I want to convert this:

[(1, 'al', 10), (2, 'bob', 20), (3, 'cam', 30)]

to

{1: ('al', 10), 2: ('bob', 20), 3: ('cam', 30)}

I can do it this way:

list = [(1, 'al', 10), (2, 'bob', 20), (3, 'cam', 30)]
dict = {}
for i in list:
   dict[i[0]] = (i[1], i[2])

But that seems gross. There must be a better way with dict() and zip() or something.

Thanks!

Upvotes: 2

Views: 1191

Answers (2)

R Nar
R Nar

Reputation: 5515

dict comprehension and tuple slicing!

>>> l = [(1, 'al', 10), (2, 'bob', 20), (3, 'cam', 30)]
>>> {t[0]:t[1:] for t in l}
{1: ('al', 10), 2: ('bob', 20), 3: ('cam', 30)}

this is good because it also allows for variable sized tuples.

Upvotes: 1

chown
chown

Reputation: 52738

You can use something like this:

>>> x = [(1, 'al', 10), (2, 'bob', 20), (3, 'cam', 30)]
>>> dict([(a, (b, c)) for a, b, c in x])
{1: ('al', 10), 2: ('bob', 20), 3: ('cam', 30)}

Passing in a list of 2-tuples to dict() will give a dict using the first item in the tuple as the key and the second item as the value.

Upvotes: 4

Related Questions