Python:将元组列表转换为dict列表

时间:2017-12-14 06:51:06

标签: python python-3.x dictionary tuples

我有一个元组列表:

[('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}]

最好和最有效的方法是什么?

3 个答案:

答案 0 :(得分:6)

您可以使用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

<强>样本

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'}]

答案 1 :(得分:5)

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}]

答案 2 :(得分:1)

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)