作者:PHP界的一股清流 | 来源:互联网 | 2023-10-12 10:38
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Python:将元组列表转换为dict列表相关的知识,希望对你有一定的参考价值。
我有一个元组列表:
[('Lebron James', datetime.date(2017, 12, 23), 500), ('Julie Peralta',
datetime.date(2017, 12, 13), 1500), ('Reynaldo Pahay', datetime.date(2017, 1
2, 11), 2500)]
我想将其转换为字典列表:
[{'Name':'Lebron James','date' :datetime.date(2017, 12, 23), 'penalty':
500},{'Name:'Julie Peralta','date': datetime.date(2017, 12, 13),'penalty':
1500},{'Name:'Reynaldo Pahay','date': datetime.date(2017, 12, 11),'penalty':
2500}]
什么是最好和最有效的方法呢?
答案
您可以使用zip
功能。
import datetime
def get_list_of_dict(keys, list_of_tuples):
"""
This function will accept keys and list_of_tuples as args and return list of dicts
"""
list_of_dict = [dict(zip(keys, values)) for values in list_of_tuples]
return list_of_dict
DEMO
keys = ("name", "date", "penalty")
my_list_of_tuples = [
('Lebron James', datetime.date(2017, 12, 23), 500),
('Julie Peralta', datetime.date(2017, 12, 13), 1500),
('Reynaldo Pahay', datetime.date(2017, 12, 11), 2500)
]
print(get_list_of_dict(keys, my_list_of_tuples))
#output
#[{'date': datetime.date(2017, 12, 23), 'penalty': 500, 'name': 'Lebron James'}, {'date': datetime.date(2017, 12, 13), 'penalty': 1500, 'name': 'Julie Peralta'}, {'date': datetime.date(2017, 12, 11), 'penalty': 2500, 'name': 'Reynaldo Pahay'}]
另一答案
import datetime
data = [('Lebron James', datetime.date(2017, 12, 23), 500),
('Julie Peralta', datetime.date(2017, 12, 13), 1500),
('Reynaldo Pahay', datetime.date(2017, 12, 11), 2500)]
print([{'Name': name, 'date': date, 'penalty': penalty} for name, date, penalty in data])
# [{'Name': 'Lebron James', 'date': datetime.date(2017, 12, 23), 'penalty': 500}, {'Name': 'Julie Peralta', 'date': datetime.date(2017, 12, 13), 'penalty': 1500}, {'Name': 'Reynaldo Pahay', 'date': datetime.date(2017, 12, 11), 'penalty': 2500}]
另一答案
import datetime
lista = [('Lebron James', datetime.date(2017, 12, 23), 500), ('Julie Peralta', datetime.date(2017, 12, 13), 1500), ('Reynaldo Pahay', datetime.date(2017, 12, 11), 2500)]
output = [{"name":a[0], "date":a[1],'penalty':a[2]} for a in lista]
print(output)