jeffa.david
jeffa.david

Reputation: 45

adding dictionary data into a tupple in a python for loop

I am struggling with this, quite new working with tuples and dictionaries. I am pulling data from my models and I want to get an array combination that looks like this;

{'Home': {'completed': '2', 'ongoing': '3'}, 'Lenan School': {'completed': '1', 'ongoing': '0'}, 'test site': {'completed': '1', 'ongoing': '3'}, 'Juala': {'completed': '0', 'ongoing': '0'}}

My code looks like this;

qua_sites = quarantine_sites.objects.all().order_by('site_name')
ongoing_cases = {}
completed_cases = []
combinded_array = myDict()
for qua_site in qua_sites:
    qua_completed_contacts = quarantine_contacts.objects.filter(quarantine_site_id = qua_site.id).filter(created_at__gte = date.today()- timedelta(days=14)).count()
    qua_ongoing_contacts = quarantine_contacts.objects.filter(quarantine_site_id = qua_site.id).filter(created_at__lte = date.today()- timedelta(days=14)).count()

    combinded_array.add('ongoing',str(qua_ongoing_contacts))
    combinded_array.add('completed',str(qua_completed_contacts))
    print("------")
    print(combinded_array)

    ongoing_cases[qua_site.site_name] = combinded_array
    print(ongoing_cases)

The combined_array keeps being overwritten by the last value. My print output is like this;

------
{'completed': '2', 'ongoing': '3'}
{'Home': {'completed': '2', 'ongoing': '3'}}
------
{'completed': '1', 'ongoing': '0'}
{'Home': {'completed': '1', 'ongoing': '0'}, 'Juala': {'completed': '1', 'ongoing': '0'}}
------
{'completed': '1', 'ongoing': '3'}
{'Home': {'completed': '1', 'ongoing': '3'}, 'Lenan School': {'completed': '1', 'ongoing': '3'}, 
'Juala': {'completed': '1', 'ongoing': '3'}}
------
{'completed': '0', 'ongoing': '0'}
{'Home': {'completed': '0', 'ongoing': '0'}, 'Lenan School': {'completed': '0', 'ongoing': '0'}, 
'test site': {'completed': '0', 'ongoing': '0'}, 'Juala': {'completed': '0', 'ongoing': '0'}}

How can I achieve the array combination that I want, like sample above. Thanks in advance.

Upvotes: 0

Views: 31

Answers (2)

Gergely Szerovay
Gergely Szerovay

Reputation: 159

Lists in Python are passed by reference, so all items in 'ongoing_cases' references to the same list instance, that's why the values were overwritten.

You should make a copy of 'combinded_array' in each iteration:

    ongoing_cases[qua_site.site_name] = combinded_array.copy()

Upvotes: 1

shx2
shx2

Reputation: 64328

The problem is that you only have one myDict object, and you keep adding references of that same object to ongoing_cases, and then changing it. This effectively changes the value of all entries in ongoing_cases (because they reference the same object).

To fix this, create a new object (combinded_array = myDict()) inside the loop.

Upvotes: 1

Related Questions