Python Forum
From Dictionaries to Matrix. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: From Dictionaries to Matrix. (/thread-17571.html)



From Dictionaries to Matrix. - dervast - Apr-16-2019

Hi
I have a rather complicated task.

I would like to turn the keys of my dictionaries to columns of a matrix (or columns of a data frame).

1.Not all dictionaries have all the keys so when creating the columns of matrix and dataframes and at the same time different dictionaries have same keys.
2. The rows will refer to the dictionary. Dictionaries are named with a number at the end _1,_2,_3. So each row should have dictionary values filled under the appropriate column.

My idea for now is to build two for loops.
A.One for loop for going through each dictionary separately. From dictionary_1 to dictionary_10. Get keys. Append key to the list of column names, only if it does not exist already.
B. Then a second loop for each elements of each dictionary. Find which is the appropriate column for each key and write the value.

Is there though a more straightforward way to do that in python. Two nested for loops, does not look very optimal and I am sure that python is quite advanced for handling such tasks.

Thanks
Alex


RE: From Dictionaries to Matrix. - Larz60+ - Apr-16-2019

so long as you don't nest the loops, and run one after the other, this method will be quite fast.