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

การวนลูปผ่าน Dictionary ใน Python


ในบทความนี้ เราจะเรียนรู้เกี่ยวกับการวนลูป/การเดินทางผ่าน Dictionary ใน Python 3.x (หรือเวอร์ชันก่อนหน้า)

Dictionary คือลำดับของคู่ key-value ที่ไม่มีลำดับ ดัชนีสามารถเป็นชนิดข้อมูล immutable ใดๆ และเรียกว่า keys ระบุภายในวงเล็บปีกกาเช่นกัน

วิธีที่ 1 - ใช้ Iterables โดยตรง

ตัวอย่างโค้ด

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# วนลูปผ่านสตริง
for value in dict_inp:
    print(value, end='')

ผลลัพธ์

trason

วิธีที่ 2 - ใช้ Iterables สำหรับค่าของ Dictionary

ตัวอย่างโค้ด

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# วนลูปผ่านสตริง
for value in dict_inp.values():
    print(value, end='')

ผลลัพธ์

oilpit

วิธีที่ 3 - ใช้ Keys เป็นดัชนี

ตัวอย่างโค้ด

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# วนลูปผ่านสตริง
for value in dict_inp:
    print(dict_inp[value], end='')

ผลลัพธ์

oilpit

วิธีที่ 4 - ใช้ Keys และ Values ของ Dictionary

ตัวอย่างโค้ด

dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# วนลูปผ่านสตริง
for value, char in dict_inp.items():
    print(value, ":", char, end=" ")

ผลลัพธ์

t : o r : i a : l s : p o : i n : t

สรุป

ในบทความนี้ เราได้เรียนรู้การวนลูป/การเดินทางผ่าน Dictionary ใน Python