http://www.trytoprogram.com/python-programming/python-dictionary/

จริงๆแล้วในการเชื่อม API ระหว่าง FE กับ BE ส่วนใหญ่จะใช้ json เป็นรูปแบบในการรับส่งข้อมูล ซึ่ง json จริงๆแล้วก็คือ String ชุดนึงที่มี format แต่การจะนำไปใช้งานใน Python ได้จะต้อง แปลงให้เป็น dictionary (Python) ติดตามได้ที่นี่นะคับ

ในบทความนี้จะแนะนำ Dictionary methods ที่ต้องรู้ เพราะได้ใช้บ่อยแน่ๆ ดูกันเลย

key + value เราจะเรียกว่า items นะ
  1. clear()
  2. copy()
  3. fromKeys()
  4. get()
  5. items()
  6. keys()
  7. pop()
  8. popitem()
  9. setdefault()
  10. update()
  11. values()

ลองสร้าง dictionary ขั้นมาดังนี้นะคับ

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
  1. clear() : จะลบ elements ทั้งหมดออกไปจาก dict เลยนะคับ
    Syntax: dictionary.clear()
car.clear()        # เหลือแค่ {} เท่านั้น

2. copy() : copy dict เพิ่มขึ้นมา และ assign ค่าเข้าตัวแปรได้เลย
Syntax : dictionary.copy()

x = car.copy()
print(x) # จะได้ dict อีกชุดนึงเลยที่เหมือนกันทุกอย่าง

3. fromkeys() : Returns a dictionary with the specified keys and value
จะสร้าง dict จาก key ที่เราระบุไว้ใน list (or tuple) ส่วน value เป็น optional ถ้าไม่ระบุจะได้ค่า None
Syntax : dict.fromkeys(keys, value)

x = ['key1', 'key2', 'key3']
y = 500

thisdict = dict.fromkeys(x, y)
print(thisdict)
# --------------------------------------
# output:
# {'key1': 500, 'key2': 500, 'key3': 500}

ประโยชน์ของการใช้ fromkeys() อย่างนึงคือ เราสามารถนำมาจัดการกับ list ที่ซ้ำกันได้ โดยที่ index ยังอยู่ที่เดิม (โดยยึดตัวที่เจอก่อนเป็นหลัก)

จัดการ list ที่ซ้ำกันด้วย dict.fromkeys()

4. get() : อันนี้ใช้บ่อยนะคับ คือ ไป get ค่า value ออกมา โดยใส่เป็น key เข้าไป
Syntax : dictionary.get(keyname, value)

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.get('brand') # กรณีมี key 'brand' นะ
y = car.get("price", 15000) # กรณีที่ไม่เจอ key 'price' กำหนด default ได้

print(x) # Ford <class 'str'>
print(y) # 15000 <class 'int'>

ใน used case จริงๆ ที่มีการเปรียบเทียบและต้อง if-else เยอะๆ เราสามารถใช้ dict + get() แทนได้ และโค้ดจะดูสวยงามกว่า readable มากกว่า

Applied dict + get() to compare like if-else

5. items() : จะคืนค่าออกมากเป็น view object ในลักษณะของ tuples ที่อยู่ใน list, ซึ่งมี key-value pairs มาจาก dictionary นั่นแหละ
Syntax : dictionary.items()

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.items()

car["year"] = 2018 # เปลี่ยนค่า value ใหม่จาก 1964 เป็น 2018

print(x)
# --------------------------------------
# output:
# dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 2018)])

สำหรับ Used case ของการใช้ items ลองยกตัวอย่างแบบนี้นะคับ

กรณีต้องการทั้ง key + values ของ dict เราจะใช้ items() มาช่วย

6. keys() : จะคืนค่า keys ทั้งหมดจาก dicts ออกมาเป็น list
Syntax : dictionary.keys()

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.keys()
print(x)

car["color"] = "white" # เพิ่ม key + value เข้าไปได้ด้วย
print(x)
# --------------------------------------
# output:
# dict_keys(['brand', 'model', 'year'])
# dict_keys(['brand', 'model', 'year', 'color'])

7. pop() : เอา element ที่ระบุจาก key ออกไป จากนั้นใน dict ก้อจะไม่มี key + value ชุดนั้นแล้ว
Syntax : dictionary.pop(keyname, defaultvalue)

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.pop("model") # เอาชุดนี้ออกไป "model":"Mustang" เก็บลงตัวแปร x

print(x)
print(car)
# --------------------------------------
# output:
# Mustang # ค่าจากตัวแปร x ที่ pop value ออกมา
# {'brand': 'Ford', 'year': 1964} # ไม่มี key model อีกแล้ว

8. popitem() : เป็นการ remove จาก item ล่าสุดเลย (ไม่ต้องระบุ argument นะ)
Syntax : dictionary.popitem()

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"color": "Black"
}

x = car.popitem()

print(x)
print(car)
# --------------------------------------
# output:
# ('color', 'Black') # ตัวที่ถูก remove ออกนะ
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

9. setdefault() : เป็นการ set default (insert key and value) ลงไปใน dictในกรณีที่ไม่มีคีย์ที่ระบุไว้ , แต่ถ้ามี key ที่ระบุไว้แล้วก้อแค่ return specified value ออกมา
Syntax : dictionary.setdefault(keyname, value)

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.setdefault("model", "Bronco")
# ถ้าใน dict ไม่มี "model" ก็จะ insert ค่าชุดนี้ให้เลย แต่ถ้ามี "model" แล้วก้อไม่ทำอะไร

print(x)
print(car)
# --------------------------------------
# output:
# Mustang # setdefault() จะ return value ออกมาในกรณีที่เจอคีย์นั้นๆ
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

10. update() : ใช้บ่อยนะ update key and value เข้าไปเลยซื่อๆ
Syntax : dictionary.update(iterable)

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(car) # car ก่อน update
car.update({"color": "White"})
# car.update(color='White') # เขียนแบบนี้ก็ได้นะ มีค่าเท่ากับบรรทัดบนเลย
print(car) # car หลังจาก update()
# --------------------------------------
# output:
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}

จริงๆแล้ว เรายังสามารถเพิ่ม key, value เข้าไปแบบนี้ก้อได้นะ มีค่าเท่ากับการใช้ .update() เลยนะ

car['name'] = 'ดำทมิฬ'
print(car)
# --------------------------------------
# output:
# {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White', 'name': 'ดำทมิฬ'}

11. values() : ตรงข้ามกับ keys() นะคับ อันนี้คือ จะ return the values
Syntax : dictionary.values()

car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

x = car.values()
print(x)
# --------------------------------------
# output:
# dict_values(['Ford', 'Mustang', 1964])

แล้วพบกันใหม่คับ

Used case:

  1. ที่ใช้บ่อยๆ ในกรณีที่เราต้องการเช็คว่า dict ตัวนี้มี key ที่เราต้องใช้ไหม สามารถตรวจเช็คได้ง่ายๆแบบนี้เลย

เมื่อ activity_date_dict มีค่าแบบนี้

ค่าของ activity_date_dict

เราจะเช็คว่า ถ้าคำนี้ check_in_date_time ไม่ได้มีอยู่ใน key ของ dict ที่ชื่อ activity_date_dict ก็จะให้สร้าง activity_date_dict ด้วยคีย์ check_in_date_time นี้ขึ้นมา

for queryset in activity_queryset:
if queryset['type'] == ActivityType.CHECK_IN:
check_in_date_time = queryset['date_time'].date()
if check_in_date_time not in activity_date_dict:
activity_date_dict[check_in_date_time] = {
'check_in': queryset.get('date_time'),
'check_out': queryset.get('check_in_pair__check_out__date_time'),
'extra_type': queryset.get('extra_type')
}
else:
activity_date_dict[check_in_date_time]['check_out'] = \
queryset.get('check_in_pair__check_out__date_time')f

หรือ simple case จะเป็นแบบนี้

การเช็คว่าใน dict มี key ที่เราตามหาไหม

2. อีกกรณี การ apply ใช้ dict จะทำให้ code เราดูง่ายขึ้น และทำงานได้ไวกว่าการใช้ multiple if เพราะไม่ต้องมาเช็คทุกๆอันของ if ตามรูปเปรียบเทียลด้านล่าครับ

Compare between multiple if vs dict

3. อีกกรณีคือ เมื่อต้องการเปรียบเทียบว่า มี key นั้นๆใน dict ไหมเราสามารถนำ map มาประยุกต์ใช้ได้ เช่น ในเคสนี้คือ ทำให้ key เป็น lower ก่อน เพื่อให้ compare กันได้ => reference

ข้อ 4 นะ เป็นการ map เพื่อเปลี่ยน key ใน dict ให้เป็น lower ก่อนที่จะนำไปเช็คใน if

4. ตัวอย่างการทำ for loop ใน dict แบบเท่ๆนะ

5. การ sort in dict ด้วย template ที่เรากำหนดไว้

6. กรณีที่เราต้องการเปลี่ยน value ใน dict เราสามารถใช้ update() ในข้อ 10 ด้านบนโดยระบุ key เข้าไปได้เลย แบบตัวอย่างข้างบนนะคับ แต่ถ้าเราต้องการ update ชื่อ key เป็นชื่อใหม่ล่ะ จะมีวิธีการแบบนี้นะคับ

การเปลี่ยนชื่อคีย์ ให้เป็นชื่อใหม่ที่เราต้องการ

PS:
คุณสมบัตินึงของ dictionary คือ จะต้องไม่มี key ที่ซ้ำกันนะ แต่ถ้าเมื่อไหร่ที่มี key ซ้ำกันใน collection, ตัวภาษาจะเลือก key ที่เป็น latest เช่น

d = {2:30, 1:10, 3:30, 1:40}
print(d)

# output (จะไม่มี 1:10 ตัวหน้านะ เพราะมี key ที่ซ้ำกับตัวหลัง)
# {2: 30, 1: 40, 3: 30}

ก่อนจบ Article นี้อยากพามาดู Trick ในการใช้ dict ที่อาจจะยังไม่รู้กันนะคับ

  1. สร้าง dict ด้วย dict() ก็ได้นะ
    - ข้อดีแบบนี้คือ key เราไม่ต้องใส่ quote นะ
Create dict with { } or dict()

2. Combine dict เราสามารถใช้ ** ได้เลยนะ
- จริงๆแล้ว เราเรียกการใช้ ** ว่า unpack key-value นั่นเอง

Combine dict by **

3. Convert list of tuple to dict

Use dict() to covert list of tuple

4. สร้าง dict แบบเท่ๆ

สร้าง dict จาก for-loop
จิงๆ แล้วรูปนี้กับรูปบน ได้ค่าเหมือนกันนะ (แค่เขียนแบบ one line เท่กว่า)

- สร้าง Nested for-loop to dict

Nested for-loop to dict

--

--