简体   繁体   中英

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.

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

>>> 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 .

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 :

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]

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