简体   繁体   English

使用每个元组的关键部分将元组列表转换为字典

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

How can this be done the python way :)这怎么能用python的方式完成:)

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将元组列表转换为字典,为每个元组赋予不同的键 - Convert a list of tuples to dictionary, giving each tuple a different key 将元组的元组转换为具有键值对的字典 - Convert tuple of tuples to a dictionary with key value pair 根据元组值将元组列表转换为字典 - Convert a list of tuples to a dictionary, based on tuple values 如何将元组列表转换为列表字典,并将元组中的公共项作为字典的键? - How to convert list of tuples as dictionary of lists with common item from tuple as key of dictionary? 如何将元组列表转换为以索引为键的字典 - How to convert list of tuples to dictionary with index as key python将元组列表转换为复合键字典 - python convert list of tuples to composite key dictionary Django模板——迭代一个元组列表,每个元组都是一个字符串,字典 - Django template - iterate a list of tuples, each tuple is a string, dictionary 熊猫如何将数据帧转换为元组字典,元组使用1 col作为键,其余部分作为形式的元组(col2:col3) - pandas how to convert a dataframe into a dictionary of tuples tuple using 1 col as key and the rest as a tuple of form (col2:col3) 将列表转换为元组列表,每个元组中的项目重复值 - Convert list to list of tuples with repeated value of item in each tuple 在元组列表中搜索元组的一部分 - Search for a part of a tuple in a list of tuples
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM