Search code examples
pythonpostgresqlplpy

How to store two different values returned from query into list data types to be used later(plpy python)


I need to store two values, "id" and "name" returned from sql query into a variable which I can use later. Can I use list for this purpose. I want to store values from sql at once and then only to refer to the stored value. I was able to do so but with only one value (id), but now I need to store both id and name together. the purpose is to do string comparision and based on it, its corresponding id is to be assigned.

for example ,first i tried to retrieve data from database by rv = plpy.execute (select id,name from aa) Now I need to store these two values somewhere in two varaible for example, lets say id in storevalueID and name in storevalueName so later I can do things like, if someXname = Replace(storeValueName("hello","")) then assign its concerned id to some varaible lile xID = storevalueID, I am not sure if we can do this , but i need to do something like this.

Any help will be appreciated..


Solution

  • I'm not sure I understand your question completely. But if you were previously storing a list of "id"s:

    mylist = []
    mylist.append(id1)  # or however you get your id values
    mylist.append(id2)
    # ..
    

    so mylist is something like [1, 2, 3], then you can simply use tuples to store more than one element that are associated together:

    mylist = []
    mylist.append( (id1, name1) )
    mylist.append( (id2, name2) )
    # ..
    

    Now mylist is something like [ (1, 'Bob'), (2, 'Alice'), (3, 'Carol')]. You can perform string comparisons on the second element of each tuple in your list:

    mylist[0][1] == 'Bob'  # True
    mylist[1][2] == 'Alice'  # True
    

    Update I just saw the updated question. In plypy, you should be able to access the variables like this:

    for row in rv:
        the_id = row['id']
        name = row['name']
    

    using the column names. See this page for more information.