简体   繁体   中英

Convert list of tuples to a dictionary using as key part of each tuple

How can this be done the python way :)

results = [(1,2,3), (2,5,6), (7,8,9)] 
results_set = {}
for r in results:
    results_set[(r[0], r[1])] = r[2]
return results_set

Use a dictionary comprehension :

results = [(1,2,3), (2,5,6), (7,8,9)] 

print({(x, y) : z for x, y, z in results})

Output

{(1, 2): 3, (2, 5): 6, (7, 8): 9}

You can use iterable unpacking:

lst = [(1,2,3), (2,5,6), (7,8,9)]

{tuple(k): v for *k, v in lst}
# {(1, 2): 3, (2, 5): 6, (7, 8): 9}

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