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

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

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

给定字典列表,转换为有序键字典,每个键包含字典作为其嵌套值。

方法 #1:使用循环 + enumerate()

这是可以执行此任务的粗暴方式。在此,我们使用 enumerate 遍历索引和值并创建自定义所需的字典。

Python3
# Python3 code to demonstrate working of 
# Convert Dictionaries List to Order Key Nested dictionaries
# Using loop + enumerate()
  
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
  
# printing original list
print("The original list : " + str(test_list))
  
# using enumerate() to extract key to map with dict values 
res = dict()
for idx, val in enumerate(test_list):
    res[idx] = val
      
# printing result 
print("The constructed dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert Dictionaries List to Order Key Nested dictionaries
# Using dictionary comprehension + enumerate() 
  
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
  
# printing original list
print("The original list : " + str(test_list))
  
# dictionary comprehension encapsulating result as one liner
res = {idx : val for idx, val in enumerate(test_list)}
      
# printing result 
print("The constructed dictionary : " + str(res))


输出
The original list : [{'Gfg': 3, 4: 9}, {'is': 8, 'Good': 2}, {'Best': 10, 'CS': 1}]
The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}

方法 #2:使用字典理解 + enumerate()

这与上述方法类似,唯一的区别是使用字典理解而不是循环来执行封装任务。

Python3

# Python3 code to demonstrate working of 
# Convert Dictionaries List to Order Key Nested dictionaries
# Using dictionary comprehension + enumerate() 
  
# initializing lists
test_list = [{"Gfg" : 3, 4 : 9}, {"is": 8, "Good" : 2}, {"Best": 10, "CS" : 1}]
  
# printing original list
print("The original list : " + str(test_list))
  
# dictionary comprehension encapsulating result as one liner
res = {idx : val for idx, val in enumerate(test_list)}
      
# printing result 
print("The constructed dictionary : " + str(res))
输出
The original list : [{'Gfg': 3, 4: 9}, {'is': 8, 'Good': 2}, {'Best': 10, 'CS': 1}]
The constructed dictionary : {0: {'Gfg': 3, 4: 9}, 1: {'is': 8, 'Good': 2}, 2: {'Best': 10, 'CS': 1}}