Python 程序 – 从列表创建字典

pythonserver side programmingprogramming更新于 2025/10/22 14:04:17

当需要从列表创建字典时,使用‘dict’方法、简单迭代和‘setdefault’方法创建字典。

示例

下面是相同的演示 −

my_dict = dict()
print("An empty dictionary has been created")
my_value_list = ['15', '14', '13', '12', '16']

print("列表为: " )
print(my_value_list)

my_value_list.sort()
print("The list after sorting is :")
print(my_value_list)

for value in my_value_list:
   for element in range(int(value), int(value) + 2):
      my_dict.setdefault(element, []).append(value)

print("The resultant dictionary is : ")
print(my_dict)

输出

An empty dictionary has been created
列表为:
['15', '14', '13', '12', '16']
The list after sorting is :
['12', '13', '14', '15', '16']
The resultant dictionary is :
{12: ['12'], 13: ['12', '13'], 14: ['13', '14'], 15: ['14', '15'], 16: ['15', '16'], 17: ['16']}

解释

  • 创建一个空字典。

  • 定义一个列表并显示在控制台上。

  • 使用排序方法对列表进行排序并显示在控制台上。

  • 迭代列表,并将默认值添加到空字典中,并将值附加到字典中。

  • 这被分配给结果。

  • 这在控制台上显示为输出。


相关文章


有用资源