Python|将列表字典拆分为字典列表
从一种数据类型到另一种数据类型的转换在编程的各个方面都是必不可少的。无论是开发还是竞争性编程。因此,了解它是非常有用和必要的。
让我们讨论一些可以将列表字典转换为相应字典列表的方法。
方法#1:使用列表推导
我们可以使用列表推导作为单行替代方案来执行各种简单的任务,以更简洁的代码提供可读性。我们可以遍历每个字典元素并相应地继续构造字典列表。
# Python3 code to demonstrate
# to convert dictionary of list to
# list of dictionaries
# using list comprehension
# initializing dictionary
test_dict = { "Rash" : [1, 3], "Manjeet" : [1, 4], "Akash" : [3, 4] }
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# using list comprehension
# to convert dictionary of list to
# list of dictionaries
res = [{key : value[i] for key, value in test_dict.items()}
for i in range(2)]
# printing result
print ("The converted list of dictionaries " + str(res))
The original dictionary is : {‘Rash’: [1, 3], ‘Manjeet’: [1, 4], ‘Akash’: [3, 4]}
The converted list of dictionaries [{‘Rash’: 1, ‘Manjeet’: 1, ‘Akash’: 3}, {‘Rash’: 3, ‘Manjeet’: 4, ‘Akash’: 4}]
方法 #2:使用zip()
这种方法使用了两次zip
函数,第一次是我们需要将所有列表的特定索引值压缩为一个,第二次是获取特定索引的所有值并使用相应的键进行压缩。
# Python3 code to demonstrate
# to convert dictionary of list to
# list of dictionaries
# using zip()
# initializing dictionary
test_dict = { "Rash" : [1, 3], "Manjeet" : [1, 4], "Akash" : [3, 4] }
# printing original dictionary
print ("The original dictionary is : " + str(test_dict))
# using zip()
# to convert dictionary of list to
# list of dictionaries
res = [dict(zip(test_dict, i)) for i in zip(*test_dict.values())]
# printing result
print ("The converted list of dictionaries " + str(res))
The original dictionary is : {‘Rash’: [1, 3], ‘Akash’: [3, 4], ‘Manjeet’: [1, 4]}
The converted list of dictionaries [{‘Rash’: 1, ‘Akash’: 3, ‘Manjeet’: 1}, {‘Rash’: 3, ‘Akash’: 4, ‘Manjeet’: 4}]