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

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

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

有时,在使用Python字典时,我们可能会遇到一个问题,我们需要将字典列表转换为嵌套记录字典,获取字典列表值的每个索引并将其展平。这类问题可以在很多领域都有应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是可以解决此问题的方法之一。在此,我们以暴力方式执行任务,迭代每个列表值索引并为其指定一个键。

Python3
# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using loop
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using loop
res =[{} for idx in range(len(test_list))]
idx = 0
for sub in test_list:
    for key, val in sub.items():
        for ele in val:
            res[idx][key] = ele
            idx += 1
        idx = 0
         
# printing result
print("Records after conversion : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
keys = [list(sub.keys())[0] for sub in test_list]
vals = zip(*[val for sub in test_list for val in sub.values()])
res = [dict(zip(keys, val)) for val in vals]
 
# printing result
print("Records after conversion : " + str(res))


输出 :
原始列表是:[{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
转换后的记录:[{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5,“是”:3,“最佳”:1}]

方法 #2:使用列表理解 + zip()
这是我们可以执行此任务的另一种方式。在此,我们分两步执行任务,首先,我们提取所有键,然后使用 zip() 相应地配对值。

Python3

# Python3 code to demonstrate working of
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
 
# initializing list
test_list = [{'Gfg' : [5, 6, 5]}, {'is' : [10, 2, 3]}, {'best' : [4, 3, 1]}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Convert Dictionary Value list to Dictionary List
# Using list comprehension + zip()
keys = [list(sub.keys())[0] for sub in test_list]
vals = zip(*[val for sub in test_list for val in sub.values()])
res = [dict(zip(keys, val)) for val in vals]
 
# printing result
print("Records after conversion : " + str(res))
输出 :
原始列表是:[{'Gfg': [5, 6, 5]}, {'is': [10, 2, 3]}, {'best': [4, 3, 1]}]
转换后的记录:[{'Gfg': 5, 'is': 10, 'best': 4}, {'Gfg': 6, 'is': 2, 'best': 3}, {'Gfg': 5,“是”:3,“最佳”:1}]