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

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

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

给定列表值和键列表,将这些值转换为字典列表形式的键值对。

方法#1:使用循环+字典理解

这是可以执行此任务的方式之一。在此,我们使用字典理解执行映射值。使用循环执行迭代。

Python3
# Python3 code to demonstrate working of 
# Convert List to List of dictionaries
# Using dictionary comprehension + loop
  
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing key list 
key_list = ["name", "number"]
  
# loop to iterate through elements
# using dictionary comprehension
# for dictionary construction
n = len(test_list)
res = []
for idx in range(0, n, 2):
    res.append({key_list[0]: test_list[idx], key_list[1] : test_list[idx + 1]})
  
# printing result 
print("The constructed dictionary list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert List to List of dictionaries
# Using zip() + list comprehension
  
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing key list 
key_list = ["name", "number"]
  
# using list comprehension to perform as shorthand
n = len(test_list)
res = [{key_list[0]: test_list[idx], key_list[1]: test_list[idx + 1]}
       for idx in range(0, n, 2)]
  
# printing result 
print("The constructed dictionary list : " + str(res))


输出

方法#2:使用字典理解+列表理解

以上功能的组合就是用来解决这个问题的。在此,我们执行与上述方法类似的任务。但不同之处在于它作为速记执行。

Python3

# Python3 code to demonstrate working of 
# Convert List to List of dictionaries
# Using zip() + list comprehension
  
# initializing lists
test_list = ["Gfg", 3, "is", 8, "Best", 10, "for", 18, "Geeks", 33]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing key list 
key_list = ["name", "number"]
  
# using list comprehension to perform as shorthand
n = len(test_list)
res = [{key_list[0]: test_list[idx], key_list[1]: test_list[idx + 1]}
       for idx in range(0, n, 2)]
  
# printing result 
print("The constructed dictionary list : " + str(res))
输出