简体   繁体   中英

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM