Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to point to a variable dynamically using str to update its value

I want to update some lists they are named like

ACL = []
ANL = []
APL = []
# more around 50+ 

I also have these names in the form of str inside a tuple

CHOICES = [ 'ACL', 'ANL', 'APL' ]

Now I’m making a query into the database when I’m getting the results of ACL I want to update the ACL list. There’s no problem in querying data and appending it to the list. But my problem is I have to query and append each list independently. But I want to utilize the choices, iterating them and updating the relative list

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

That’s my current approach:

acl_filtered_data = [{"results" : "result"} for j in qs if j.choice == 'ANL']
ACL.append(acl_filtered_data)

And the same for the other choices.

So here I want to run a loop for all the available choices and append it into the related list.

for i in CHOICES:
    filtered_data = [{"results" : "result"} for j in qs if j.choice == i]
    # here I want to point ACL = [] and append it with the filtered_data and also keep repeating for the others 
    # I'm not sure how I can do that.

I need your help to achieve this kind of logic. Thanks

>Solution :

Create a dictionary or list of tuples, like you had before, where each string references the corresponding list.

Then on each iteration you have a reference to the list that you need to append to.

ACL = []
ANL = []
APL = []
CHOICES = {'ACL': ACL, 'ANL': ANL, 'APL': APL}
  
...

for key, value in CHOICES.items():
    filtered_data = [{"results" : "result"} for j in qs if j.choice == key]
    value.append(filtered_data)

Or using tuples.

ACL = []
ANL = []
APL = []
CHOICES = [('ACL', ACL), ('ANL', ANL), ('APL', APL)]
  
...

for text, lst in CHOICES:
    filtered_data = [{"results" : "result"} for j in qs if j.choice == text]
    lst.append(filtered_data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading