Python 将嵌套列表转换为字典

Python 将嵌套列表转换为字典,python,python-3.x,Python,Python 3.x,我已经找到了几个解决方案,但都涉及到使用numpy和复杂代码,我还是一个初学者,还没有学会这方面的知识。任何人都可以提供一个更简单的解决方案(即使用循环)如何将嵌套列表转换为字典。下面是我尝试过的示例问题和代码: 将原始列表转换为字典,使每个子列表的键为:“power1”, #依次为“power2”、“power3”、“power4”、“power5” 我尝试过执行以下代码,但它只打印最后一个内部列表: {'powers1': [1, 32], 'powers2': [1, 32], 'powe

我已经找到了几个解决方案,但都涉及到使用numpy和复杂代码,我还是一个初学者,还没有学会这方面的知识。任何人都可以提供一个更简单的解决方案(即使用循环)如何将嵌套列表转换为字典。下面是我尝试过的示例问题和代码:

将原始列表转换为字典,使每个子列表的键为:“power1”, #依次为“power2”、“power3”、“power4”、“power5”

我尝试过执行以下代码,但它只打印最后一个内部列表:

{'powers1': [1, 32], 'powers2': [1, 32], 'powers3': [1, 32], 'powers4': [1, 32], 'powers5': [1, 32]}
这是我尝试过的代码:

powers = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]] #this is the original list

powers_dictionary = {}
list_powers=["powers1","powers2","powers3","powers4","powers5"]

for ele in powers: 
  for i in list_powers:
    powers_dictionary.update({i:ele})

print(powers_dictionary)
试试这个:

keys = ["powers1","powers2","powers3","powers4","powers5"]
values = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]]
dictionary = dict(zip(keys, values))

另一个版本,使用显式循环:

powers_dictionary = {}

list_powers=["powers1","powers2","powers3","powers4","powers5"]
powers = [ [1, 2, 3, 4, 5, 6], [1, 4, 9, 16, 25], [1, 8, 27, 64], [1, 16, 81], [1, 32]] #this is the original list

for idx, power in enumerate(list_powers):
    powers_dictionary[power] = []
    for p in powers[idx]:
        powers_dictionary[power].append(p)

print(powers_dictionary)
印刷品:

{'powers1': [1, 2, 3, 4, 5, 6], 'powers2': [1, 4, 9, 16, 25], 'powers3': [1, 8, 27, 64], 'powers4': [1, 16, 81], 'powers5': [1, 32]}


注意:将
dict()
zip()
一起使用更高效、更简洁。

dict(zip(列出电源,电源))
?感谢您的帮助,但我想问一下,有没有什么方法可以使用for循环来实现这一点?为什么要使用
for
循环
dict
zip
效率更高。