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

วิธีส่ง Dictionary เป็นอาร์กิวเมนต์ให้ฟังก์ชัน Python

ส่ง dictionary เข้าฟังก์ชัน แล้ววนลูปผ่าน key-value pairs ด้วย .items() (Python 3) หรือ .iteritems() (Python 2)

ตัวอย่าง

d = {'a': 1, 'b': 2, 'c': 3}

def f(dict_arg):
    for k, v in dict_arg.items():
        print(k, 2 * v)

f(d)

ผลลัพธ์

a 2
c 6
b 4

ลำดับอาจแตกต่างไปได้ เพราะ dictionary ไม่มีลำดับ (Python < 3.7) แต่ Python 3.7+ รักษาลำดับการแทรก