إتقان دوال الـ Dictionary (Dictionary Methods) في بايثون

في هذا الدرس، سنتعلم كيفية استخدام الدوال المدمجة (Methods) التي تتيح لنا التعامل مع الـ Dictionaries في لغة بايثون بكل سهولة وكفاءة. هذه الدوال هي أدوات قوية تساعدنا في الوصول إلى البيانات، تعديلها، وحتى تنظيف الـ Dictionary بالكامل.

ما هي دوال الـ Dictionary (Dictionary Methods)؟

دوال الـ Dictionary هي وظائف (Functions) مدمجة داخل Objects الـ Dictionary. يمكننا استدعاؤها مباشرة بعد اسم الـ Dictionary باستخدام النقطة .. تخيل أن الـ Dictionary مثل صندوق أدوات، وكل دالة هي أداة مختلفة لها وظيفة محددة.

# Example of a simple dictionary
student = {"name": "Ahmed", "age": 20, "major": "Engineering"}

# Using .keys() method to see the keys
print(student.keys())  # Will print: dict_keys(['name', 'age', 'major'])

في المثال أعلاه، keys() هي إحدى دوال الـ Dictionary التي تُرجع لنا جميع المفاتيح الموجودة فيه.

الدوال الأساسية للوصول إلى البيانات

1. الدالة get()

هذه الدالة آمنة للاستخدام عندما لا نكون متأكدين من وجود مفتاح معين في الـ Dictionary. بدلاً من ظهور خطأ إذا كان المفتاح غير موجود، تُرجع الدالة قيمة افتراضية (عادة None).

my_dict = {"a": 1, "b": 2}

# Try to access an existing key
value1 = my_dict.get("a")
print(value1)  # Output: 1

# Try to access a non-existent key
value2 = my_dict.get("c")
print(value2)  # Output: None (because key 'c' does not exist)

# We can specify an alternative default value
value3 = my_dict.get("c", "Key not found!")
print(value3)  # Output: "Key not found!"

2. الدوال keys() و values() و items()

هذه الدوال تعطينا نظرة سريعة على محتويات الـ Dictionary.

  • .keys(): تُرجع List تحتوي على جميع المفاتيح.
  • .values(): تُرجع List تحتوي على جميع القيم.
  • .items(): تُرجع List تحتوي على جميع الأزواج (مفتاح، قيمة) على شكل tuples.
car = {"brand": "Toyota", "model": "Camry", "year": 2022}

print(car.keys())   # Output: dict_keys(['brand', 'model', 'year'])
print(car.values()) # Output: dict_values(['Toyota', 'Camry', 2022])
print(car.items())  # Output: dict_items([('brand', 'Toyota'), ('model', 'Camry'), ('year', 2022)])

هذه الدوال مفيدة جداً عندما نريد التكرار (Loop) خلال محتويات الـ Dictionary، وهو ما سنتعلمه لاحقاً.

الدوال الأساسية لتعديل البيانات

1. الدالة update()

تسمح لنا هذه الدالة بإضافة عدة عناصر إلى الـ Dictionary دفعة واحدة، أو تحديث قيمة مفتاح موجود.

# Basic dictionary
person = {"name": "Fatima"}

# We want to add age and city
new_info = {"age": 25, "city": "Riyadh"}

# Use update to add new information
person.update(new_info)
print(person)  # Output: {'name': 'Fatima', 'age': 25, 'city': 'Riyadh'}

# We can also update directly
person.update(age=26, job="Developer") # Note updating 'age' value and adding 'job'
print(person)  # Output: {'name': 'Fatima', 'age': 26, 'city': 'Riyadh', 'job': 'Developer'}

2. الدالة setdefault()

دالة ذكية تقوم بأمرين:

  1. إذا كان المفتاح موجوداً في الـ Dictionary، تُرجع قيمته.
  2. إذا كان المفتاح غير موجود، تقوم بإضافته إلى الـ Dictionary بالقيمة الافتراضية التي نحددها.
book = {"title": "The Days", "author": "Taha Hussein"}

# Key exists, it will return its value only
author_name = book.setdefault("author", "Unknown Author")
print(author_name) # Output: Taha Hussein
print(book) # Dictionary unchanged: {'title': 'The Days', 'author': 'Taha Hussein'}

# Key does not exist, it will be added
book_pages = book.setdefault("pages", 300)
print(book_pages) # Output: 300
print(book) # Output: {'title': 'The Days', 'author': 'Taha Hussein', 'pages': 300}

الدوال الأساسية لحذف البيانات

1. الدالة pop()

تقوم هذه الدالة بإزالة عنصر من الـ Dictionary بناءً على المفتاح المحدد، وتُرجع قيمته. هذا مفيد عندما نريد استخدام القيمة المحذوفة لاحقاً.

fruits = {"apple": "apple", "banana": "banana", "orange": "orange"}

# Remove element with key "banana" and return its value
removed_fruit = fruits.pop("banana")
print(removed_fruit) # Output: banana
print(fruits)        # Output: {'apple': 'apple', 'orange': 'orange'}

# If we try to remove a non-existent key, an error occurs unless we specify a default value
# removed_fruit = fruits.pop("grape") # Will cause KeyError
safe_removal = fruits.pop("grape", "fruit not found")
print(safe_removal) # Output: fruit not found

2. الدالة popitem()

تقوم بإزالة آخر زوج (مفتاح، قيمة) تم إضافته إلى الـ Dictionary وتُرجعه. في الإصدارات الحديثة من بايثون (3.7+)، الـ Dictionaries تحفظ ترتيب الإضافة.

colors = {"red": "red", "blue": "blue"}
colors["green"] = "green" # Add a new color

# Delete the last added item (green: green)
last_item = colors.popitem()
print(last_item) # Output: ('green', 'green')
print(colors)    # Output: {'red': 'red', 'blue': 'blue'}

3. الدالة clear()

هذه الدالة بسيطة جداً؛ فهي تزيل جميع العناصر من الـ Dictionary، تاركة إياه فارغاً.

temp_dict = {"x": 1, "y": 2, "z": 3}
print(temp_dict) # Output: {'x': 1, 'y': 2, 'z': 3}

temp_dict.clear()
print(temp_dict) # Output: {}

الدالة copy() و fromkeys()

1. الدالة copy()

تقوم بإنشاء نسخة سطحية (Shallow Copy) من الـ Dictionary. هذا مهم عندما نريد عمل تغييرات على نسخة دون التأثير على الـ Dictionary الأصلي.

original = {"name": "Ali"}
# Copy the dictionary
new_copy = original.copy()

# Add an element to the new copy only
new_copy["age"] = 30

print("Original:", original) # Output: Original: {'name': 'Ali'}
print("Copy:", new_copy) # Output: Copy: {'name': 'Ali', 'age': 30}

2. الدالة fromkeys()

هذه دالة منهجية (Static Method)، مما يعني أننا نستدعيها من اسم الـ Class dict نفسه وليس من Object Dictionary محدد. وظيفتها هي إنشاء Dictionary جديد من List مفاتيح، مع تعيين نفس القيمة لجميعها.

# Create a new dictionary where all key values are 0
keys_list = ['math', 'science', 'history']
new_dict = dict.fromkeys(keys_list, 0)

print(new_dict) # Output: {'math': 0, 'science': 0, 'history': 0}

خلاصة الدرس

تعلمنا في هذا الدرس أهم دوال الـ Dictionary التي تمنحنا تحكماً كاملاً في البيانات المخزنة داخله. تذكر أن:

  • استخدام get() أكثر أماناً من الوصول المباشر بالمفتاح.
  • keys(), values(), و items() ممتازة لاستكشاف محتوى الـ Dictionary.
  • update() و setdefault() هما الأداتان الرئيسيتان للإضافة والتحديث.
  • pop(), popitem(), و clear() تستخدم للحذف بطرق مختلفة.
  • copy() تنشئ نسخة مستقلة، و fromkeys() تنشئ قاموساً جديداً من List مفاتيح.