convert List with dictionaries to a single dictionary - 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: convert List with dictionaries to a single dictionary (/thread-32129.html) |
convert List with dictionaries to a single dictionary - iamaghost - Jan-22-2021 Hey guys, i have a matrix with lots of zeroes. In order to make the code more efficient i want to write code, that takes the rows and colums as indexes and their values as a dictionary. I managed to do the task but i could not figure out how to make a dictionary out of a list with dictionaries. heres the Code: matrix = [[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]] dictionary = [] row = -1 # to make row start at 0 for i in matrix: # row row += 1 column = -1 for j in i: # column column += 1 if j != 0: dictionary.append({(row, column): j}) print(dictionary)the output is: [{(0, 3): 1}, {(2, 1): 2}, {(4, 3): 3}] thats a list containing dicts. But i want a a single dictionary with with tuples as keys containing row and column indexes and the matrix elements as values. Thanks RE: convert List with dictionaries to a single dictionary - Serafim - Jan-22-2021 (Jan-22-2021, 02:28 PM)iamaghost Wrote: Hey guys, Why do you use a list called dictionary? That doesn't turn it into a dictionary. Use a dictionary instead: matrix = [[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]] dictionary = dict() row = -1 # to make row start at 0 for i in matrix: # row row += 1 column = -1 for j in i: # column column += 1 if j != 0: dictionary[(row, column)]= j print(dictionary) RE: convert List with dictionaries to a single dictionary - deanhystad - Jan-22-2021 Are you familiar with sparse matrices? I don't know if this fits in well with what you are trying to do. https://cmdlinetips.com/2018/03/sparse-matrices-in-python-with-scipy/ RE: convert List with dictionaries to a single dictionary - iamaghost - Jan-22-2021 (Jan-22-2021, 03:39 PM)deanhystad Wrote: Are you familiar with sparse matrices? I don't know if this fits in well with what you are trying to do. Yea so my matrix in this example is a sparse matrix. But since i dont need those zeroes there i wanted describe a sparse matrix in form of a dict. The reply of @Serafim helped me out :) |