ในบทความนี้ เราจะเรียนรู้เกี่ยวกับการวนซ้ำ/การข้ามผ่านของพจนานุกรมใน Python 3.x หรือก่อนหน้านั้น
พจนานุกรมคือลำดับของคู่คีย์-ค่าที่ไม่เรียงลำดับ ดัชนีสามารถเป็นแบบที่ไม่เปลี่ยนรูปแบบใดก็ได้และเรียกว่าคีย์ นอกจากนี้ยังระบุไว้ในวงเล็บปีกกา
วิธีที่ 1 − ใช้ iterables โดยตรง
ตัวอย่าง
dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# Iterate over the string
for value in dict_inp:
print(value, end='') ผลลัพธ์
trason
วิธีที่ 2 - การใช้ iterables สำหรับค่าของพจนานุกรม
ตัวอย่าง
dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# Iterate over the string
for value in dict_inp.values():
print(value, end='') ผลลัพธ์
oilpit
วิธีที่ 3 - การใช้คีย์เป็นดัชนี
ตัวอย่าง
dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# Iterate over the string
for value in dict_inp:
print(dict_inp[value], end='') ผลลัพธ์
oilpit
วิธีที่ 4 - การใช้คีย์และค่าของพจนานุกรม
ตัวอย่าง
dict_inp = {'t':'u','t':'o','r':'i','a':'l','s':'p','o':'i','n':'t'}
# Iterate over the string
for value,char in dict_inp.items():
print(value,":",char, end=" ") ผลลัพธ์
t : o r : i a : l s : p o : i n : t
บทสรุป
ในบทความนี้ เราได้เรียนรู้เกี่ยวกับการวนซ้ำ/ข้ามผ่านพจนานุกรมใน Python