简体   繁体   中英

Use first element from list of tuples as dictionary key

How can I take a list of tuples like the following:

test = [('A', 1, 8, 4), ('B', 2, 6, 2), ('C', 3, 6, 2)]

And make a dictionary that uses the first element in each tuple as the key

output = {'A': (1, 8, 4), 'B':(2, 6, 2), 'C': (3, 6, 2)}

If the original list was a list of tuples of length two, then dict(test) would have worked fine, but that does not work in this case.

I could do [i[0] for i in test] to extract the first element of each tuple, but I was thinking there is probably a more efficient/Pythonic and generalizable way of doing this.

Thanks!

您可以使用字典理解:

output = {item[0]: item[1:] for item in test}

Using dict

Ex:

test = [('A', 1, 8, 4), ('B', 2, 6, 2), ('C', 3, 6, 2)]
print( dict((i[0], i[1:]) for i in test) )

Output:

{'A': (1, 8, 4), 'C': (3, 6, 2), 'B': (2, 6, 2)}

You could expand on your proposed answer and do an dictionary comprehension instead. Try something along these lines:

output = {i[0]: i[1:] for i in test}

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