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

แปลง List ของ Key-Value เป็น Flat Dictionary ใน Python


ภาพรวม

เมื่อต้องการแปลง Dictionary ที่มีคู่ Key-Value เป็น Flat List สามารถใช้ Dictionary Comprehension วนลูปผ่าน Dictionary และ Zip ด้วยเมธอด zip() เมธอด Zip รวม iterable เป็น Tuple และคืนผลลัพธ์

ตัวอย่างโค้ด

from itertools import product
my_dict = {'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
print("The dictionary is : ")
print(my_dict)
my_result = dict(zip(my_dict['month_num'], my_dict['name_of_month']))
print("The flattened dictionary is: ")
print(my_result)

ผลลัพธ์ตัวอย่าง

The dictionary is : {'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']}
The flattened dictionary is: {1: 'Jan', 2: 'Feb', 3: 'March', 4: 'Apr', 5: 'May', 6: 'June'}

คำอธิบาย

  • Import package ที่จำเป็น
  • นิยาม Dictionary และแสดงบนคอนโซล
  • ใช้เมธอด zip() ผูก Key และ Value ของ Dictionary แล้วแปลงกลับเป็น Dictionary
  • กำหนดให้ตัวแปร
  • แสดงผลลัพธ์บนคอนโซล