Python | 您所在的位置:网站首页 › 列表改成字典 › Python |
Python提供了很多灵活性来处理不同类型的数据结构。为了更好地使用或更好地分析数据,可能需要将一种数据结构转换为另一种数据结构。在本文中,我们将看到如何将Python集转换为Python字典。 使用zip和dict dict()可用于获取输入参数并将其转换为字典。我们还使用zip函数将键和值分组在一起,这些键和值最终成为字典中的键值对。 例 现场演示 12345list_keys = {1,2,3,4} list_values = {'Mon','Tue','Wed','Thu'} new_dict = dict(zip(list_keys, list_values)) print(new_dict) print(type(new_dict))输出量 运行上面的代码将为我们提供以下结果- 12{1: 'Mon', 2: 'Tue', 3: 'Thu', 4: 'Wed'}使用dict.fromkeys 当我们需要一个具有不同键的字典但每个键的值相同时,可以使用如下所示的方法。 例 现场演示 1234list_keys = {1,2,3,4} new_dict = dict.fromkeys(list_keys,'Mon') print(new_dict) print(type(new_dict))输出量 运行上面的代码将为我们提供以下结果- 12{1: 'Mon', 2: 'Mon', 3: 'Mon', 4: 'Mon'}使用字典理解 我们使用与以前的方法类似的方法,除了在这种情况下,我们有字典理解功能。 例 现场演示 1234list_keys = {1,2,3,4} new_dict = {element:'Tue' for element in list_keys} print(new_dict) print(type(new_dict))输出量 运行上面的代码将为我们提供以下结果- 12{1: 'Tue', 2: 'Tue', 3: 'Tue', 4: 'Tue'} |
CopyRight 2018-2019 实验室设备网 版权所有 |