What is the output of the following? “`python from itertools import groupby data = [(‘a’,1),(‘a’,2),(‘b’,3),(‘b’,4),(‘a’,5)] result = {k: list(v) for k, v in groupby(data, key=lambda x: x[0])} print(result) “`
Python DeveloperHard
Python Developer — Hard
What is the output of the following? “`python from itertools import groupby data = [(‘a’,1),(‘a’,2),(‘b’,3),(‘b’,4),(‘a’,5)] result = {k: list(v) for k, v in groupby(data, key=lambda x: x[0])} print(result) “`
Explanation
The correct output is {'a': [('a',5)], 'b': [('b',3),('b',4)]}. The groupby function groups the data based on the first element of each tuple. The lambda function x
Key points
The groupby function groups data based on a specified key