otto
otto

Reputation: 2033

python convert list of dict to list of tuple

how can I convert a list of dict to a list of tuple? Input:

[{'x': 0.4711900100474648, 'y': 0.6294374442355883}, {'x': 0.4732473419066774, 'y': 0.629306809190704}, {'x': 0.47373722332499346, 'y': 0.6274779185623242}, {'x': 0.47363924704133026, 'y': 0.6273908285324014}, {'x': 0.4731493656230142, 'y': 0.6261715681134813}, {'x': 0.4722349203088243, 'y': 0.6252571227992915}, {'x': 0.47210428526394, 'y': 0.62521357778433}, {'x': 0.4709285698599815, 'y': 0.6253442128292143}, {'x': 0.47024273587433907, 'y': 0.62612802309852}, {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

I want this:

[(0,47..., 0.62...),(...,...)]

I tried this:

tupleList = [tuple(val['x'], val['y']) for dic in listOfDict for key,val in dic.items()]

I get error TypeError: 'float' object is not subscriptable

Upvotes: 2

Views: 914

Answers (2)

Patrick Artner
Patrick Artner

Reputation: 51643

If you are using python 3.7+ and inserted the keys in x,y order (like done here) you could simply use the dict.values() of each inner dict. The values() will be in key (==input) order as well:

data = [{'x': 0.4711900100474648, 'y': 0.6294374442355883}, 
        {'x': 0.4732473419066774, 'y': 0.629306809190704}, 
        {'x': 0.47373722332499346, 'y': 0.6274779185623242}, 
        {'x': 0.47363924704133026, 'y': 0.6273908285324014}, 
        {'x': 0.4731493656230142, 'y': 0.6261715681134813}, 
        {'x': 0.4722349203088243, 'y': 0.6252571227992915}, 
        {'x': 0.47210428526394, 'y': 0.62521357778433}, 
        {'x': 0.4709285698599815, 'y': 0.6253442128292143}, 
        {'x': 0.47024273587433907, 'y': 0.62612802309852}, 
        {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

tup = [tuple(d.values()) for d in data]

Output:

[(0.4711900100474648, 0.6294374442355883), (0.4732473419066774, 0.629306809190704), 
 (0.47373722332499346, 0.6274779185623242), (0.47363924704133026, 0.6273908285324014), 
 (0.4731493656230142, 0.6261715681134813), (0.4722349203088243, 0.6252571227992915), 
 (0.47210428526394, 0.62521357778433), (0.4709285698599815, 0.6253442128292143), 
 (0.47024273587433907, 0.62612802309852), (0.4706019822477708, 0.6283052738465912)]

Upvotes: 5

Or Y
Or Y

Reputation: 2118

list_of_points = [{'x': 0.4711900100474648, 'y': 0.6294374442355883}, {'x': 0.4732473419066774, 'y': 0.629306809190704}, {'x': 0.47373722332499346, 'y': 0.6274779185623242}, {'x': 0.47363924704133026, 'y': 0.6273908285324014}, {'x': 0.4731493656230142, 'y': 0.6261715681134813}, {'x': 0.4722349203088243, 'y': 0.6252571227992915}, {'x': 0.47210428526394, 'y': 0.62521357778433}, {'x': 0.4709285698599815, 'y': 0.6253442128292143}, {'x': 0.47024273587433907, 'y': 0.62612802309852}, {'x': 0.4706019822477708, 'y': 0.6283052738465912}]

points_tuples = [(p['x'], p['y']) for p in list_of_points] 

Upvotes: 5

Related Questions