将元组列表转换为 dict 列表

2022-01-20 00:00:00 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, 12, 11), 2500)]

我想把它转换成字典列表:

I want to convert it into a list of dictionary:

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

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

What's the best and efficient way to do it?


解决方案

你可以使用 zip 函数.

You can make use of zip function.

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

相关文章