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

การสร้างพจนานุกรมโดยใช้เนื้อหารายการใน Python


การเปลี่ยนประเภทคอลเลกชันจากประเภทหนึ่งไปเป็นอีกประเภทหนึ่งเป็นความต้องการที่พบบ่อยมากในหลาม ในบทความนี้เราจะมาดูกันว่าเราสร้างพจนานุกรมได้อย่างไรเมื่อมีหลายรายการ ความท้าทายคือการสามารถรวมรายการทั้งหมดเหล่านี้เพื่อสร้างพจนานุกรมหนึ่งพจนานุกรมที่รองรับค่าทั้งหมดเหล่านี้ในรูปแบบค่าคีย์ของพจนานุกรม

มีซิป

ฟังก์ชัน zip สามารถใช้เพื่อรวมค่าของรายการต่างๆ ดังที่แสดงด้านล่าง ในตัวอย่างด้านล่าง เราได้นำรายการสามรายการเป็นอินพุตและรวมเข้าด้วยกันเป็นพจนานุกรมเดียว รายการหนึ่งระบุคีย์สำหรับพจนานุกรม และอีกสองรายการเก็บค่าที่จัดเก็บไว้สำหรับแต่ละคีย์

ตัวอย่าง

key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']

# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))


# Dictionary creation
res = {key: {'Day': day, 'Fruit': fruit} for key, day, fruit in
zip(key_list, day_list, fruit_list)}

# Result
print("The final dictionary : \n" ,res)

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'Fruit': 'Apple'}, 2: {'Day': 'Saturday', 'Fruit': 'Banana'}, 3: {'Day': 'Sunday', 'Fruit': 'Grape'}}

พร้อมแจงนับ

ฟังก์ชันแจกแจงเพิ่มตัวนับเป็นคีย์ของวัตถุแจกแจง ดังนั้นในกรณีของเรา เราจะใส่ key_list เป็นพารามิเตอร์ให้กับ

ตัวอย่าง

key_list = [1, 2,3]
day_list = ['Friday', 'Saturday','Sunday']
fruit_list = ['Apple','Banana','Grape']

# Given Lists
print("Given key list : " + str(key_list))
print("Given day list : " + str(day_list))
print("Given fruit list : " + str(fruit_list))


# Dictionary creation
res = {val : {"Day": day_list[key], "age": fruit_list[key]}
for key, val in enumerate(key_list)}

# Result
print("The final dictionary : \n" ,res)

ผลลัพธ์

การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -

Given key list : [1, 2, 3]
Given day list : ['Friday', 'Saturday', 'Sunday']
Given fruit list : ['Apple', 'Banana', 'Grape']
The final dictionary :
{1: {'Day': 'Friday', 'age': 'Apple'}, 2: {'Day': 'Saturday', 'age': 'Banana'}, 3: {'Day': 'Sunday', 'age': 'Grape'}}