البرمجة

إضافة قيم متعددة لمفتاح في قاموس Python

In Python, you can achieve this by using a dictionary of lists. Each key in the dictionary corresponds to a list, and you can append values to the list associated with each key. Here’s an example:

python
# Initialize an empty dictionary Dict = {} # Add values to the dictionary Dict.setdefault("xxx", []).append(3) Dict.setdefault("YYY", []).append(9) Dict.setdefault("xxx", []).append(4) Dict.setdefault("YYY", []).append(10) # Print the dictionary print(Dict)

This will output:

arduino
{'xxx': [3, 4], 'YYY': [9, 10]}

In this way, you can add multiple values to a dictionary key one by one without overwriting the previous values.

المزيد من المعلومات

في الحل السابق، قمنا باستخدام setdefault للحصول على قيمة القيد إذا كان موجودًا، وإذا لم يكن، سيتم إنشاء قيد جديد بقيمة قائمة فارغة. ثم قمنا بإضافة القيم إلى القوائم المرتبطة بكل مفتاح باستخدام append.

تجنبنا استخدام الطريقة التقليدية لتعيين القيم مباشرة (Dict[key] = value) لأنها ستستبدل القيمة السابقة إذا كانت موجودة.

يمكنك استخدام هذا النمط لإضافة المزيد من القيم إلى أي مفتاح في القاموس دون خطر فقدان القيم السابقة.

زر الذهاب إلى الأعلى