简体   繁体   中英

Converting a dictionary to a list of lists

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.

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))
# 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]]

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]]

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM