Reputation: 182
Let's say I got a dictionary defined this way: d ={(0, 1): 1, (1, 0): 4, (1, 3): 7, (2, 3): 11}
I want to convert it to a list in a way that each key represents that index of the value within the nested list and index of the nested list itself in the list. Each nested list has 4 items, indices with no defined values are set to 0.
I suck at describing. Here's what I want my function to return: lst = [[0,1,0,0], [4,0,0,7], [0,0,0,11]]
. Here's my unfinished, non working code:
def convert):
lst = []
for i in range(len(d)):
lst += [[0,0,0,0]] # adding the zeros first.
for i in d:
for j in range(4):
lst[j] = list(i[j]) # and then the others.
Upvotes: 0
Views: 98
Reputation: 71451
You can use a list comprehension:
d ={(0, 1): 1, (1, 0): 4, (1, 3): 7, (2, 3): 11}
m_x, m_y = map(max, zip(*d))
m = [[d.get((b, a), 0) for a in range(m_y+1)] for b in range(m_x+1)]
Ouptut:
[[0, 1, 0, 0], [4, 0, 0, 7], [0, 0, 0, 11]]
Upvotes: 0
Reputation: 3022
# Input
example_d = {(0, 1): 1, (1, 0): 4, (1, 3): 7, (2, 3): 11}
def get_list(d):
# Figure out the required lengths by looking at the highest indices
max_list_idx = max(x for (x, _), _ in d.items())
max_sublist_idx = max(y for (_, y), _ in d.items())
# Create an empty list with the max sizes
t = [[0] * (max_sublist_idx + 1) for _ in range(max_list_idx + 1)]
# Fill out the empty list according to the input
for (x, y), value in d.items():
t[x][y] = value
return t
print(get_list(example_d))
# Output: [[0, 1, 0, 0], [4, 0, 0, 7], [0, 0, 0, 11]]
Upvotes: 1
Reputation: 20669
You can try this.
max_x=max(d,key=lambda x:x[0])[0] # For finding max number of rows
# 2
max_y=max(d,key=lambda x:x[1])[1] # For finding max of columns
# 3
new_list=[[0]*(max_y+1) for _ in range(max_x+1)] # Creating a list with max_x+1 rows and max_y+1 columns filled with zeros
# [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
for (x,y),v in d:
new_list[x][y]=v
new_list
# [[0, 1, 0, 0], [4, 0, 0, 7], [0, 0, 0, 11]]
Upvotes: 0
Reputation: 1673
How about:
for (x,y), value in d.items():
list[x][y] = value
Here is the entire function, which also creates the correct list size automatically
def convert(d):
# Figure out how big x and y can get
max_x = max([coord[0] for coord in d.keys()])
max_y = max([coord[1] for coord in d.keys()])
# Create a 2D array with the given dimensions
list = [[0] * (max_y + 1) for ix in range(max_x + 1)]
# Assign values
for (x,y), value in d.items():
list[x][y] = value
return list
if __name__ == "__main__":
d ={(0, 1): 1, (1, 0): 4, (1, 3): 7, (2, 3): 11}
print(convert(d))
Upvotes: 1