Click here to Skip to main content
15,937,127 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a function to check for some data in few tables and create a dictionary using its two specific values.i am only able to add the current value and the previous value is deleted.

What I have tried:

def update_dict(detail):
    printerdict={}
    toner_printer_id=Toners.objects.get(id=detail.toner_model_id)
    printdescription=Items.objects.get(id=toner_printer_id.toner_printer.id)
    print_description=printdescription.description
    print(print_description)
    tonerid=update_items.detailId
    ptdescription=print_description
    # for tonerid,ptdescription in printerdict:
    if tonerid not in printerdict:
            printerdict[tonerid]=ptdescription
    for k,v in printerdict.items():
        print(k,v)
Posted
Updated 27-Aug-22 8:57am

The problem is that every time you call update_dict it creates a new printerdict variable. So it only ever adds one item to the dictionary and then terminates the function. You need to create the dictionary as a global, so it exists beyond the lifetime of the function. So change it to:
Python
printerdict={}
def update_dict(detail):
    # rest of the code here

See 9.2. Python Scopes and Namespaces at 9. Classes — Python 3.10.6 documentation[^]
 
Share this answer
 
Comments
Muneer Mohd 27-Aug-22 14:54pm    
@Richard MacCutchan, thank you,so much.it works like a charm.now the results are as expected.
printerdict={}
def update_dict(detail):
    printerdict={}
    toner_printer_id=Toners.objects.get(id=detail.toner_model_id)
    printdescription=Items.objects.get(id=toner_printer_id.toner_printer.id)
    print_description=printdescription.description
    print(print_description)
    tonerid=update_items.detailId
    ptdescription=print_description
    # for tonerid,ptdescription in printerdict:
    if tonerid not in printerdict:
            printerdict[tonerid]=ptdescription
    for k,v in printerdict.items():
        print(k,v)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900