如何在python中填充字典?

Dir*_*der 4 python dictionary dictionary-comprehension

我有一个像这样的列表: N = [[a,b,c],[d,e,f],[g,h,i]]

我想创建一个包含 N 中每个列表的所有第一个值的字典,以便我拥有;

d = {1:[a,d,g],2:[b,e,h],3:[c,f,i]}
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多东西,但我无法弄清楚。我得到的最接近的:

d = {}
for i in range(len(N)):
    count = 0
    for j in N[i]:
        d[count] = j
        count+=1
Run Code Online (Sandbox Code Playgroud)

但这并没有给我正确的字典?我真的很感激这方面的任何指导,谢谢。

Ioa*_*mas 5

您可以使用字典理解(我将 N 与 4 个项目一起使用,以避免混淆):

N=[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i'],['w', 'j', 'l']]

{i+1:[k[i] for k in N] for i in range(len(N[0]))}

#{1: ['a', 'd', 'g', 'w'], 2: ['b', 'e', 'h', 'j'], 3: ['c', 'f', 'i', 'l']}
Run Code Online (Sandbox Code Playgroud)

  • @bruno,这是我首先想到的,但正确的输出是我当前的解决方案 (2认同)