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

วิธีคืนค่า Dictionary จากฟังก์ชัน Python

สามารถคืนค่า dictionary ได้โดยสร้าง dict แล้ว return กลับไป

ตัวอย่าง

def foo():
    d = dict()
    d['str'] = "Tutorialspoint"
    d['x'] = 50
    return d

print(foo())

ผลลัพธ์

{'x': 50, 'str': 'Tutorialspoint'}

นอกจากนี้ยังสามารถใช้ dict literal {'key': value} หรือ dict comprehension ได้เช่นกัน