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

วิธีเปลี่ยนค่าใน Python Dictionary

สามารถกำหนดค่า dictionary ให้ตัวแปรด้วย access operator [] เช่น

ตัวอย่าง

my_dict = {
    'foo': 42,
    'bar': 12.5
}
new_var = my_dict['foo']
print(new_var)

ผลลัพธ์

42

Syntax นี้ใช้ reassign ค่าที่เกี่ยวข้องกับ key ได้ เช่น

ตัวอย่าง

my_dict = {
    'foo': 42,
    'bar': 12.5
}
my_dict['foo'] = "Hello"
print(my_dict['foo'])

ผลลัพธ์

Hello