Python – 将字典列表转换为列表列表
有时,在处理Python数据时,我们可能会遇到需要将字典列表转换为列表列表的问题,这可以通过将键附加一次来简化,如果它们大部分在记录中是重复的,这样可以节省内存空间.这类问题可以在 Web 开发领域有应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘Gfg’: 123, ‘best’: 10}, {‘Gfg’: 51, ‘best’: 7}]
Output : [[‘Gfg’, ‘best’], [123, 10], [51, 7]]
Input : test_list = [{‘Gfg’ : 12}]
Output : [[‘Gfg’], [12]]
方法 #1:使用循环 + enumerate()
上述方法的组合可用于执行此任务。在此,我们使用循环和蛮力在 enumerate() 的帮助下执行迭代任务,以在结果列表中执行适当的追加。
# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
{'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
{'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
# printing original list
print("The original list is : " + str(test_list))
# Convert List of Dictionaries to List of Lists
# Using loop + enumerate()
res = []
for idx, sub in enumerate(test_list, start = 0):
if idx == 0:
res.append(list(sub.keys()))
res.append(list(sub.values()))
else:
res.append(list(sub.values()))
# printing result
print("The converted list : " + str(res))
The original list is : [{‘Akash’: 18, ‘Nikhil’: 17, ‘Akshat’: 20}, {‘Akash’: 30, ‘Nikhil’: 21, ‘Akshat’: 10}, {‘Akash’: 12, ‘Nikhil’: 31, ‘Akshat’: 19}]
The converted list : [[‘Akash’, ‘Nikhil’, ‘Akshat’], [18, 17, 20], [30, 21, 10], [12, 31, 19]]
方法#2:使用列表推导
可以使用列表理解在一行中解决此任务。在此,我们最初使用 keys() 提取键,使用 values() 提取值。
# Python3 code to demonstrate working of
# Convert List of Dictionaries to List of Lists
# Using list comprehension
# initializing list
test_list = [{'Nikhil' : 17, 'Akash' : 18, 'Akshat' : 20},
{'Nikhil' : 21, 'Akash' : 30, 'Akshat' : 10},
{'Nikhil' : 31, 'Akash' : 12, 'Akshat' : 19}]
# printing original list
print("The original list is : " + str(test_list))
# Convert List of Dictionaries to List of Lists
# Using list comprehension
res = [[key for key in test_list[0].keys()], *[list(idx.values()) for idx in test_list ]]
# printing result
print("The converted list : " + str(res))
The original list is : [{‘Akash’: 18, ‘Nikhil’: 17, ‘Akshat’: 20}, {‘Akash’: 30, ‘Nikhil’: 21, ‘Akshat’: 10}, {‘Akash’: 12, ‘Nikhil’: 31, ‘Akshat’: 19}]
The converted list : [[‘Akash’, ‘Nikhil’, ‘Akshat’], [18, 17, 20], [30, 21, 10], [12, 31, 19]]