Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรม Python – สร้างพจนานุกรมจากรายการ


เมื่อจำเป็นต้องสร้างพจนานุกรมจากรายการ พจนานุกรมจะถูกสร้างขึ้นโดยใช้วิธี 'dict' ใช้การวนซ้ำอย่างง่าย และใช้วิธี 'setdefault'

ตัวอย่าง

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

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

print("The list is : " )
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
The list is :
['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']}

คำอธิบาย

  • พจนานุกรมว่างเปล่าถูกสร้างขึ้น

  • รายการถูกกำหนดและแสดงบนคอนโซล

  • รายการถูกจัดเรียงโดยใช้วิธีการจัดเรียงและแสดงบนคอนโซล

  • รายการมีการวนซ้ำ และค่าดีฟอลต์จะถูกเพิ่มลงในพจนานุกรมเปล่า และค่าจะถูกผนวกเข้ากับพจนานุกรมด้วย

  • สิ่งนี้ถูกกำหนดให้กับผลลัพธ์

  • สิ่งนี้จะแสดงเป็นเอาต์พุตบนคอนโซล