Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct tuple from dictionary values

Tags:

python

Given a python a list of dictionary of key-value pairs i.e.

[{'color': 'red', 'value': 'high'}, {'color': 'yellow', 'value': 'low'}]

How to construct a list of tuples from the dictionary values only:

[('red', 'high'), ('yellow', 'low')]
like image 973
DevEx Avatar asked Mar 08 '23 20:03

DevEx


2 Answers

As simple as it gets:

result = [(d['color'], d['value']) for d in dictionarylist]
like image 73
RafaelLopes Avatar answered Mar 11 '23 09:03

RafaelLopes


If order is important then:

[tuple(d[k] for k in ['color', 'value']) for d in data]

Or:

[(d['color'], d['value']) for d in data]

Else without order guarantees or from an OrderedDict (or relying on Py3.6 dict):

[tuple(d.values()) for d in data]
like image 38
AChampion Avatar answered Mar 11 '23 11:03

AChampion