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

วิธี Zip Python Dictionary และ List ร่วมกัน

ฟังก์ชัน zip() สามารถใช้ Zip หนึ่ง Key-Value Pair จาก Dictionary และ Item ที่ตรงกันใน List ร่วมกัน

>>> dictionary = {'A': 1, 'B': 2, 'C': 3}
>>> num_list = [1, 2, 3]
>>> zipped = zip(dictionary.items(), num_list)
>>> zipped
<zip object at 0x000000886641B9C8>

Object Zipped นี้เมื่อแปลงเป็น List จะแสดงผลลัพธ์ดังนี้

>>> list(zipped)
[(('A', 1), 1), (('B', 2), 2), (('C', 3), 3)]