📜  Python – 将列表转换为嵌套字典

📅  最后修改于: 2022-05-13 01:54:45.157000             🧑  作者: Mango

Python – 将列表转换为嵌套字典

有时,在使用Python字典时,我们可能会遇到需要将列表转换为嵌套的问题,即每个列表值代表新的嵌套级别。这种问题可以在包括Web开发在内的许多领域中得到应用。让我们讨论可以执行此任务的特定方式。

方法:使用zip() + 列表理解
上述功能的组合可以组合起来执行此任务。在此,我们迭代压缩列表并使用列表理解呈现嵌套字典。

# Python3 code to demonstrate working of 
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
  
# initializing list
test_list1 = ["gfg", 'is', 'best']
test_list2 = ['ratings', 'price', 'score']
test_list3 = [5, 6, 7]
  
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
print("The original list 3 is : " + str(test_list3))
  
# Convert Lists to Nestings Dictionary
# Using list comprehension + zip()
res = [{a: {b: c}} for (a, b, c) in zip(test_list1, test_list2, test_list3)]
  
# printing result 
print("The constructed dictionary : " + str(res)) 
输出 :
The original list 1 is : ['gfg', 'is', 'best']
The original list 2 is : ['ratings', 'price', 'score']
The original list 3 is : [5, 6, 7]
The constructed dictionary : [{'gfg': {'ratings': 5}}, {'is': {'price': 6}}, {'best': {'score': 7}}]