迭代列表并将值添加到字典

时间:2020-05-16 17:27:36

标签: python list loops dictionary

我正在尝试创建一个字典,该字典中的值是通过迭代列表获得的。键是元组格式(i,j)。

例如如果i = 3,j = 3,则键为

(1,1),(1,2),(1,3),(2,1),(2,2),(2,3),(3,1),(3,2) ,(3,3)。

如果我的列表如下,

lst = list(range(1, 10))

我如何获得这样的字典?

{(0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9}

我尝试过:

dict = {(i,j): d for d in lst for i in range(1, i+1) for j in range(1, j+1)}

但我的词典的值严格是lst的最后一个值。这是我的输出:

>>> {(0, 0): 9, (0, 1): 9, (0, 2): 9, (1, 0): 9, (1, 1): 9, (1, 2): 9, (2, 0): 9, (2, 1): 9, (2, 2): 9}

1 个答案:

答案 0 :(得分:2)

如果您已经有元组列表list_of_tuples,那么它将起作用:

d = {L:i for i,L in enumerate(list_of_tuples)}

或者如果存在一个单独的长度为len(list_of_tuples)的列表,称为lst,那么您可以这样做

d = {L:lst[i] for i,L in enumerate(list_of_tuples)}