DevEx
DevEx

Reputation: 4561

Construct tuple from dictionary values

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')]

Upvotes: 4

Views: 10487

Answers (5)

Ma0
Ma0

Reputation: 15204

a = [{'color': 'red', 'value': 'high'}, {'color': 'yellow', 'value': 'low'}]
b = [tuple(sub.values()) for sub in a]  # [('red', 'high'), ('yellow', 'low')]

Upvotes: -3

David Golembiowski
David Golembiowski

Reputation: 175

To generalize for any class instance where self.__dict__ is defined, you can also use:

tuple([self.__dict__[_] for _,__ in self.__dict__.items()])

Upvotes: 0

Benson Wainaina
Benson Wainaina

Reputation: 49

For Dynamic List Of Dictionaries

This is what I would go with in this case, I hope I have been of help.

tuple_list = []
for li_item in list_dict:
    for k, v in li_item.items():
        tuple_list.append((k,v))

Of course there is a one liner option like this one below:

tupples = [
    [(k,v) for k, v in li_item.items()][0:] for li_item in list_dict
]

Upvotes: 0

AChampion
AChampion

Reputation: 30258

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]

Upvotes: 4

RafaelLopes
RafaelLopes

Reputation: 473

As simple as it gets:

result = [(d['color'], d['value']) for d in dictionarylist]

Upvotes: 6

Related Questions