How to concatenate structs in a loop in python










2















I am trying to search for all users in an sql database whose first names are "blah" and return that data to my html through an ajax call. I have this functioning with a single user like this:



user = db.execute(
'SELECT * FROM user WHERE genres LIKE ?', (str,)
).fetchone()
user_details =
'first': user['first'],
'last': user['last'],
'email': user['email']

y = json.dumps(user_details)
return jsonify(y)


Now for multiple users I want the struct to look something like this:



users
user1_details =
'first': user['first'],
'last': user['last'],
'email': user['email']

user2_details =
'first': user2['first'],
'last': user2['last'],
'email': user2['email']

user3_details =
'first': user3['first'],
'last': user3['last'],
'email': user3['email']




generating each user_details in a loop. I know I can use fetchall() to find all the users, but how do I concatenate the details?










share|improve this question


























    2















    I am trying to search for all users in an sql database whose first names are "blah" and return that data to my html through an ajax call. I have this functioning with a single user like this:



    user = db.execute(
    'SELECT * FROM user WHERE genres LIKE ?', (str,)
    ).fetchone()
    user_details =
    'first': user['first'],
    'last': user['last'],
    'email': user['email']

    y = json.dumps(user_details)
    return jsonify(y)


    Now for multiple users I want the struct to look something like this:



    users
    user1_details =
    'first': user['first'],
    'last': user['last'],
    'email': user['email']

    user2_details =
    'first': user2['first'],
    'last': user2['last'],
    'email': user2['email']

    user3_details =
    'first': user3['first'],
    'last': user3['last'],
    'email': user3['email']




    generating each user_details in a loop. I know I can use fetchall() to find all the users, but how do I concatenate the details?










    share|improve this question
























      2












      2








      2








      I am trying to search for all users in an sql database whose first names are "blah" and return that data to my html through an ajax call. I have this functioning with a single user like this:



      user = db.execute(
      'SELECT * FROM user WHERE genres LIKE ?', (str,)
      ).fetchone()
      user_details =
      'first': user['first'],
      'last': user['last'],
      'email': user['email']

      y = json.dumps(user_details)
      return jsonify(y)


      Now for multiple users I want the struct to look something like this:



      users
      user1_details =
      'first': user['first'],
      'last': user['last'],
      'email': user['email']

      user2_details =
      'first': user2['first'],
      'last': user2['last'],
      'email': user2['email']

      user3_details =
      'first': user3['first'],
      'last': user3['last'],
      'email': user3['email']




      generating each user_details in a loop. I know I can use fetchall() to find all the users, but how do I concatenate the details?










      share|improve this question














      I am trying to search for all users in an sql database whose first names are "blah" and return that data to my html through an ajax call. I have this functioning with a single user like this:



      user = db.execute(
      'SELECT * FROM user WHERE genres LIKE ?', (str,)
      ).fetchone()
      user_details =
      'first': user['first'],
      'last': user['last'],
      'email': user['email']

      y = json.dumps(user_details)
      return jsonify(y)


      Now for multiple users I want the struct to look something like this:



      users
      user1_details =
      'first': user['first'],
      'last': user['last'],
      'email': user['email']

      user2_details =
      'first': user2['first'],
      'last': user2['last'],
      'email': user2['email']

      user3_details =
      'first': user3['first'],
      'last': user3['last'],
      'email': user3['email']




      generating each user_details in a loop. I know I can use fetchall() to find all the users, but how do I concatenate the details?







      python sql






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 14 '18 at 1:48









      JaphyJaphy

      184




      184






















          2 Answers
          2






          active

          oldest

          votes


















          1














          Fetch all the rows after the query, then structure the results as you'd like.



          Example:



           db = mysql.connection.cursor()

          # query
          db.execute('SELECT * FROM user')

          # returned columns
          header = [x[0] for x in db.description]

          # returned rows
          results = db.fetchall()

          #data to be returned
          users_object =

          #structure results
          for result in results:
          users_object[result["user_id"]] = dict(zip(header,result))

          return jsonify(users_object)


          As you can see in under "#structure results", you just loop through the results and insert the data for each row into the users_object with key equal to "user_id" for example.



          If you want the results in an array just convert users_object into an array e.g. users_array and append the dict to the array within the loop instead






          share|improve this answer

























          • Yes, this is exactly what I was looking for. Thanks.

            – Japhy
            Nov 14 '18 at 3:54


















          0














          The keys in the desired users dictionary do not seem particularly useful so you could instead build a list of user dicts. It's easy to go directly from fetchall() to such a list:



          result = db.execute('SELECT * FROM user WHERE genres LIKE ?', (str,))
          users = ['first': first, 'last': last, 'email': email for first, last, email in result.fetchall()]
          return jsonify(users)


          To return a dict containing the user list:



          return jsonify('users': users)





          share|improve this answer
























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292039%2fhow-to-concatenate-structs-in-a-loop-in-python%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            Fetch all the rows after the query, then structure the results as you'd like.



            Example:



             db = mysql.connection.cursor()

            # query
            db.execute('SELECT * FROM user')

            # returned columns
            header = [x[0] for x in db.description]

            # returned rows
            results = db.fetchall()

            #data to be returned
            users_object =

            #structure results
            for result in results:
            users_object[result["user_id"]] = dict(zip(header,result))

            return jsonify(users_object)


            As you can see in under "#structure results", you just loop through the results and insert the data for each row into the users_object with key equal to "user_id" for example.



            If you want the results in an array just convert users_object into an array e.g. users_array and append the dict to the array within the loop instead






            share|improve this answer

























            • Yes, this is exactly what I was looking for. Thanks.

              – Japhy
              Nov 14 '18 at 3:54















            1














            Fetch all the rows after the query, then structure the results as you'd like.



            Example:



             db = mysql.connection.cursor()

            # query
            db.execute('SELECT * FROM user')

            # returned columns
            header = [x[0] for x in db.description]

            # returned rows
            results = db.fetchall()

            #data to be returned
            users_object =

            #structure results
            for result in results:
            users_object[result["user_id"]] = dict(zip(header,result))

            return jsonify(users_object)


            As you can see in under "#structure results", you just loop through the results and insert the data for each row into the users_object with key equal to "user_id" for example.



            If you want the results in an array just convert users_object into an array e.g. users_array and append the dict to the array within the loop instead






            share|improve this answer

























            • Yes, this is exactly what I was looking for. Thanks.

              – Japhy
              Nov 14 '18 at 3:54













            1












            1








            1







            Fetch all the rows after the query, then structure the results as you'd like.



            Example:



             db = mysql.connection.cursor()

            # query
            db.execute('SELECT * FROM user')

            # returned columns
            header = [x[0] for x in db.description]

            # returned rows
            results = db.fetchall()

            #data to be returned
            users_object =

            #structure results
            for result in results:
            users_object[result["user_id"]] = dict(zip(header,result))

            return jsonify(users_object)


            As you can see in under "#structure results", you just loop through the results and insert the data for each row into the users_object with key equal to "user_id" for example.



            If you want the results in an array just convert users_object into an array e.g. users_array and append the dict to the array within the loop instead






            share|improve this answer















            Fetch all the rows after the query, then structure the results as you'd like.



            Example:



             db = mysql.connection.cursor()

            # query
            db.execute('SELECT * FROM user')

            # returned columns
            header = [x[0] for x in db.description]

            # returned rows
            results = db.fetchall()

            #data to be returned
            users_object =

            #structure results
            for result in results:
            users_object[result["user_id"]] = dict(zip(header,result))

            return jsonify(users_object)


            As you can see in under "#structure results", you just loop through the results and insert the data for each row into the users_object with key equal to "user_id" for example.



            If you want the results in an array just convert users_object into an array e.g. users_array and append the dict to the array within the loop instead







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 '18 at 3:04

























            answered Nov 14 '18 at 2:51









            AlexMikaAlexMika

            857




            857












            • Yes, this is exactly what I was looking for. Thanks.

              – Japhy
              Nov 14 '18 at 3:54

















            • Yes, this is exactly what I was looking for. Thanks.

              – Japhy
              Nov 14 '18 at 3:54
















            Yes, this is exactly what I was looking for. Thanks.

            – Japhy
            Nov 14 '18 at 3:54





            Yes, this is exactly what I was looking for. Thanks.

            – Japhy
            Nov 14 '18 at 3:54













            0














            The keys in the desired users dictionary do not seem particularly useful so you could instead build a list of user dicts. It's easy to go directly from fetchall() to such a list:



            result = db.execute('SELECT * FROM user WHERE genres LIKE ?', (str,))
            users = ['first': first, 'last': last, 'email': email for first, last, email in result.fetchall()]
            return jsonify(users)


            To return a dict containing the user list:



            return jsonify('users': users)





            share|improve this answer





























              0














              The keys in the desired users dictionary do not seem particularly useful so you could instead build a list of user dicts. It's easy to go directly from fetchall() to such a list:



              result = db.execute('SELECT * FROM user WHERE genres LIKE ?', (str,))
              users = ['first': first, 'last': last, 'email': email for first, last, email in result.fetchall()]
              return jsonify(users)


              To return a dict containing the user list:



              return jsonify('users': users)





              share|improve this answer



























                0












                0








                0







                The keys in the desired users dictionary do not seem particularly useful so you could instead build a list of user dicts. It's easy to go directly from fetchall() to such a list:



                result = db.execute('SELECT * FROM user WHERE genres LIKE ?', (str,))
                users = ['first': first, 'last': last, 'email': email for first, last, email in result.fetchall()]
                return jsonify(users)


                To return a dict containing the user list:



                return jsonify('users': users)





                share|improve this answer















                The keys in the desired users dictionary do not seem particularly useful so you could instead build a list of user dicts. It's easy to go directly from fetchall() to such a list:



                result = db.execute('SELECT * FROM user WHERE genres LIKE ?', (str,))
                users = ['first': first, 'last': last, 'email': email for first, last, email in result.fetchall()]
                return jsonify(users)


                To return a dict containing the user list:



                return jsonify('users': users)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 14 '18 at 7:57

























                answered Nov 14 '18 at 3:00









                mhawkemhawke

                58.6k75481




                58.6k75481



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53292039%2fhow-to-concatenate-structs-in-a-loop-in-python%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    27

                    Top Tejano songwriter Luis Silva dead of heart attack at 64

                    Category:Rhetoric