Python - Merge List value Keys to Matrix

Python - Merge List value Keys to Matrix

To merge a list of dictionaries into a matrix (2D list), where each dictionary's keys become the first row (header) and their corresponding values from each dictionary fill the subsequent rows.

Given this list of dictionaries:

data = [ {'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9} ] 

We want to produce:

[ ['a', 'b', 'c'], [1, 2, 3], [4, 5, 6], [7, 8, 9] ] 

Here's how you can do it:

data = [ {'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}, {'a': 7, 'b': 8, 'c': 9} ] # Assuming all dictionaries have the same keys headers = list(data[0].keys()) matrix = [headers] for dic in data: row = [dic[key] for key in headers] matrix.append(row) for row in matrix: print(row) 

This code will print the desired matrix. Note that this assumes all dictionaries in the list have the same keys.


More Tags

heidisql resnet jquery-mobile custom-function cloudinary singly-linked-list zooming npm-scripts codeigniter-3 task

More Programming Guides

Other Guides

More Programming Examples