Transform a dictionary into a list of tuples with Python
Question:
I want to transform a dictionary into a list of tuples, but doing it ‘row-wise’: the first tuple should cointain the first values, the second tuple the second values, and so on.
I have some working code, but I wonder if there is a more idiomatic way of doing it because my solution seems too verbose.
data = {
'a': [1,2,3,4],
'b': [1,2,3,5],
'c': [1,2,3,6]
}
tuple_list = []
for i, x in enumerate(data['a']):
tpl = []
for key in data:
val = data[key][i]
tpl.append(val)
tuple_list.append(tuple(tpl))
output
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 5, 6)]
Answers:
You can use zip
which iterate over several iterables in parallel, producing tuples with an item from each one.
print(list(zip(*data.values())))
# Equivalent to
# print(list(zip([1, 2, 3, 4], [1,2,3,5], [1, 2, 3, 6])))
You can do it with the following one-liner:
list(zip(*data.values()))
Explanation: data.values()
gives you a list dictionary values (in this case, lists). Next we use *
operator to unpack that list into three separate arguments for zip
function. zip
takes several iterables as arguments, and creates tuples from respective elements of each iterable. Then we just have to convert it from zip object to a list (if you’re gonna do any further processing, it might be possible to keep it as zip object).
I want to transform a dictionary into a list of tuples, but doing it ‘row-wise’: the first tuple should cointain the first values, the second tuple the second values, and so on.
I have some working code, but I wonder if there is a more idiomatic way of doing it because my solution seems too verbose.
data = {
'a': [1,2,3,4],
'b': [1,2,3,5],
'c': [1,2,3,6]
}
tuple_list = []
for i, x in enumerate(data['a']):
tpl = []
for key in data:
val = data[key][i]
tpl.append(val)
tuple_list.append(tuple(tpl))
output
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (4, 5, 6)]
You can use zip
which iterate over several iterables in parallel, producing tuples with an item from each one.
print(list(zip(*data.values())))
# Equivalent to
# print(list(zip([1, 2, 3, 4], [1,2,3,5], [1, 2, 3, 6])))
You can do it with the following one-liner:
list(zip(*data.values()))
Explanation: data.values()
gives you a list dictionary values (in this case, lists). Next we use *
operator to unpack that list into three separate arguments for zip
function. zip
takes several iterables as arguments, and creates tuples from respective elements of each iterable. Then we just have to convert it from zip object to a list (if you’re gonna do any further processing, it might be possible to keep it as zip object).