简体   繁体   English

将元组列表转换为字典,为每个元组赋予不同的键

[英]Convert a list of tuples to dictionary, giving each tuple a different key

I have a list of tuples consisting of x,y coordinates ordered in a specific way and want to convert this to a dictionary, where each tuple has a different key. 我有一个由以特定方式排序的x,y坐标组成的元组列表,并希望将其转换为字典,其中每个元组都有一个不同的键。

How should I do this? 我应该怎么做? If names is not doable, numbers would be fine as well. 如果名字不可行,数字也可以。 Eventually the goal is to plot all the different points as categories. 最终目标是将所有不同的点绘制为类别。

# list of tuples
ordered_points = [(1188.0, 751.0),(1000.0, 961.0),(984.0, 816.0),(896.0, 707.0),(802.0, 634.0),(684.0, 702.0),(620.0, 769.0)]


# what I want 
orderder_points_dict = {'pointing finger':(1188.0, 751.0), 'middle finger':(1000.0, 961.0) etc...}

If you are interested, in having just numbers as index, you can use enumerate to do this 如果您有兴趣将数字作为索引,则可以使用enumerate来执行此操作

>>> ordered_points = [(1188.0, 751.0),(1000.0, 961.0),(984.0, 816.0),(896.0, 707.0),(802.0, 634.0),(684.0, 702.0),(620.0, 769.0)]
>>> 
>>> dict(enumerate(ordered_points))
{0: (1188.0, 751.0), 1: (1000.0, 961.0), 2: (984.0, 816.0), 3: (896.0, 707.0), 4: (802.0, 634.0), 5: (684.0, 702.0), 6: (620.0, 769.0)}

Or if you have the keys in a seperate list, 或者,如果您将密钥放在单独的列表中,

>>> keys
['key0', 'key1', 'key2', 'key3', 'key4', 'key5', 'key6']
>>> 
>>> dict(zip(keys,ordered_points))
{'key0': (1188.0, 751.0), 'key1': (1000.0, 961.0), 'key2': (984.0, 816.0), 'key3': (896.0, 707.0), 'key4': (802.0, 634.0), 'key5': (684.0, 702.0), 'key6': (620.0, 769.0)}
>>>

Given a list of keys correctly ordered, you can use zip to create your dict . 给定正确排列的键列表,您可以使用zip创建dict

ordered_points = [(1188.0, 751.0), (1000.0, 961.0), ...]
keys = ['pointing finger', 'middle finger', ...]

d = dict(zip(keys, ordered_points))
# d: {'pointing finger': (1188.0, 751.0), 'middle finger': (1000.0, 961.0), ...: ...}

You can use zip : 您可以使用zip

expected_dict = dict(zip([i for i in range(len(ordered_points))],ordered_points))

Output:' 输出:

{0: (1188.0, 751.0), 1: (1000.0, 961.0), 2: (984.0, 816.0), 3: (896.0, 707.0), 4: (802.0, 634.0), 5: (684.0, 702.0), 6: (620.0, 769.0)}

If you have a list of names: 如果您有名称列表:

ordered_points = [(1188.0, 751.0),(1000.0, 961.0)]
names = ['pointing finger', 'middle finger']
mydict = {}
for count, x in enumerate(names):
    mydict[x] = ordered_points[count]

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

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