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

แปลงสองรายการเป็นพจนานุกรมใน Python


ในขณะที่รายการ Python มีชุดค่าต่างๆ อยู่ พจนานุกรมกลับมีค่าคู่หนึ่งซึ่งเรียกว่าคู่คีย์-ค่า ในบทความนี้ เราจะนำสองรายการมารวมกันเพื่อสร้างพจนานุกรม Python

มีสำหรับและลบ

เราสร้างสองซ้อนกันสำหรับลูป ในวงในจะกำหนดรายการใดรายการหนึ่งเป็นคีย์สำหรับพจนานุกรมในขณะที่ลบค่าออกจากรายการที่อยู่ด้านนอกของลูป

ตัวอย่าง

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# Empty dictionary
res = {}
# COnvert to dictionary
for key in listK:
   for value in listV:
      res[key] = value
      listV.remove(value)
      break
print("Dictionary from lists :\n ",res)

ผลลัพธ์

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

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})

มี for และ range

ทั้งสองรายการถูกรวมเข้าด้วยกันเพื่อสร้างคู่ของค่าโดยใส่ลงใน for loop ฟังก์ชัน range และ len ใช้เพื่อติดตามจำนวนขององค์ประกอบจนกว่าจะสร้างคู่ของค่าคีย์ทั้งหมด

ตัวอย่าง

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = {listK[i]: listV[i] for i in range(len(listK))}
print("Dictionary from lists :\n ",res)

ผลลัพธ์

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

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})

มีซิป

ฟังก์ชัน zip ทำสิ่งที่คล้ายกับแนวทางข้างต้น นอกจากนี้ยังรวมองค์ประกอบจากสองรายการเข้าด้วยกันเพื่อสร้างคู่คีย์และค่า

ตัวอย่าง

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = dict(zip(listK, listV))
print("Dictionary from lists :\n ",res)

ผลลัพธ์

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

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})