1

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...}
Steve
  • 353
  • 3
  • 12

4 Answers4

3

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)}
>>>
Sunitha
  • 11,777
  • 2
  • 20
  • 23
  • I want to point out that there is absolutely no advantage to having keys which are the index the item had in the list. The second part of the answer is the same as mine, so if you remove the first part of yours, I'll delete mine and upvote – Olivier Melançon Jun 25 '18 at 14:28
2

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), ...: ...}
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

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)}
Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
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]
BioFrank
  • 185
  • 1
  • 8