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

Python – สร้าง Dictionary จากลิสต์

เมื่อต้องการสร้าง dictionary จากลิสต์โดยใช้สมาชิกเป็น key และค่าเดียวกันสำหรับทุก key สามารถใช้ dict.fromkeys() ได้

ตัวอย่าง

my_list = ['Hi', 'Will', 'how', 'Python', 'cool']
print("The list is ")
print(my_list)
my_dict = dict.fromkeys(my_list, "my_value")
print(my_dict)

ผลลัพธ์

The list is ['Hi', 'Will', 'how', 'Python', 'cool']
{'Hi': 'my_value', 'Will': 'my_value', 'how': 'my_value', 'Python': 'my_value', 'cool': 'my_value'}

คำอธิบาย

  • กำหนดลิสต์สตริงและแสดงผล

  • ใช้ dict.fromkeys(keys, value) สร้าง dictionary จากลิสต์ keys กำหนด value ให้ทุก key เหมือนกัน

  • แสดงผล dictionary ที่ได้