Dinamically var in parameter of a function












3















I'm trying to call a function using a name of a var dinamically, but I don't know if this is possible, something like that:



fight_movies = list() # var how I want to use in function call
win_movies = list() # var how I want to use in function call
knowledge_movies = list() # var how I want to use in function call
biography_movies = list() # var how I want to use in function call

for genre in genres:
.... Ommited #////// Here is where I call the function
write_jsonl(genre + '_movies', genre, rating, title, genre) #here is the call of the function


def write_jsonl(movie_list, genre, rating, title, json_name):
dict = {'title': title, 'genre': genre, 'rating': rating}
movie_list.append(dict)
# print(action_movies)
with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
writer.write(movie_list)


I'm trying to pass the variable name as a list dynamically, but I'm not sure if that's possible in python, any suggestions?



Error: Traceback (most recent call last):
File "bucky.py", line 58, in <module>
web_crawling()
File "bucky.py", line 34, in web_crawling
write_jsonl(genre + '_movies', genre, rating, title, genre)
File "bucky.py", line 52, in write_jsonl
movie_list.append(dict)
AttributeError: 'str' object has no attribute 'append'









share|improve this question


















  • 9





    Don't do this. Use a dictionary.

    – Daniel Roseman
    Nov 24 '18 at 22:57






  • 1





    Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

    – Jefferson Bruchado
    Nov 24 '18 at 23:03
















3















I'm trying to call a function using a name of a var dinamically, but I don't know if this is possible, something like that:



fight_movies = list() # var how I want to use in function call
win_movies = list() # var how I want to use in function call
knowledge_movies = list() # var how I want to use in function call
biography_movies = list() # var how I want to use in function call

for genre in genres:
.... Ommited #////// Here is where I call the function
write_jsonl(genre + '_movies', genre, rating, title, genre) #here is the call of the function


def write_jsonl(movie_list, genre, rating, title, json_name):
dict = {'title': title, 'genre': genre, 'rating': rating}
movie_list.append(dict)
# print(action_movies)
with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
writer.write(movie_list)


I'm trying to pass the variable name as a list dynamically, but I'm not sure if that's possible in python, any suggestions?



Error: Traceback (most recent call last):
File "bucky.py", line 58, in <module>
web_crawling()
File "bucky.py", line 34, in web_crawling
write_jsonl(genre + '_movies', genre, rating, title, genre)
File "bucky.py", line 52, in write_jsonl
movie_list.append(dict)
AttributeError: 'str' object has no attribute 'append'









share|improve this question


















  • 9





    Don't do this. Use a dictionary.

    – Daniel Roseman
    Nov 24 '18 at 22:57






  • 1





    Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

    – Jefferson Bruchado
    Nov 24 '18 at 23:03














3












3








3








I'm trying to call a function using a name of a var dinamically, but I don't know if this is possible, something like that:



fight_movies = list() # var how I want to use in function call
win_movies = list() # var how I want to use in function call
knowledge_movies = list() # var how I want to use in function call
biography_movies = list() # var how I want to use in function call

for genre in genres:
.... Ommited #////// Here is where I call the function
write_jsonl(genre + '_movies', genre, rating, title, genre) #here is the call of the function


def write_jsonl(movie_list, genre, rating, title, json_name):
dict = {'title': title, 'genre': genre, 'rating': rating}
movie_list.append(dict)
# print(action_movies)
with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
writer.write(movie_list)


I'm trying to pass the variable name as a list dynamically, but I'm not sure if that's possible in python, any suggestions?



Error: Traceback (most recent call last):
File "bucky.py", line 58, in <module>
web_crawling()
File "bucky.py", line 34, in web_crawling
write_jsonl(genre + '_movies', genre, rating, title, genre)
File "bucky.py", line 52, in write_jsonl
movie_list.append(dict)
AttributeError: 'str' object has no attribute 'append'









share|improve this question














I'm trying to call a function using a name of a var dinamically, but I don't know if this is possible, something like that:



fight_movies = list() # var how I want to use in function call
win_movies = list() # var how I want to use in function call
knowledge_movies = list() # var how I want to use in function call
biography_movies = list() # var how I want to use in function call

for genre in genres:
.... Ommited #////// Here is where I call the function
write_jsonl(genre + '_movies', genre, rating, title, genre) #here is the call of the function


def write_jsonl(movie_list, genre, rating, title, json_name):
dict = {'title': title, 'genre': genre, 'rating': rating}
movie_list.append(dict)
# print(action_movies)
with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
writer.write(movie_list)


I'm trying to pass the variable name as a list dynamically, but I'm not sure if that's possible in python, any suggestions?



Error: Traceback (most recent call last):
File "bucky.py", line 58, in <module>
web_crawling()
File "bucky.py", line 34, in web_crawling
write_jsonl(genre + '_movies', genre, rating, title, genre)
File "bucky.py", line 52, in write_jsonl
movie_list.append(dict)
AttributeError: 'str' object has no attribute 'append'






python list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 24 '18 at 22:55









FelipeFelipe

439821




439821








  • 9





    Don't do this. Use a dictionary.

    – Daniel Roseman
    Nov 24 '18 at 22:57






  • 1





    Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

    – Jefferson Bruchado
    Nov 24 '18 at 23:03














  • 9





    Don't do this. Use a dictionary.

    – Daniel Roseman
    Nov 24 '18 at 22:57






  • 1





    Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

    – Jefferson Bruchado
    Nov 24 '18 at 23:03








9




9





Don't do this. Use a dictionary.

– Daniel Roseman
Nov 24 '18 at 22:57





Don't do this. Use a dictionary.

– Daniel Roseman
Nov 24 '18 at 22:57




1




1





Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

– Jefferson Bruchado
Nov 24 '18 at 23:03





Yeah, you're right Filip Mlynarski, but I believe what he's trying to do is to pass this dynamically so he doesn't have to keep calling the function multiple times and creating multiple ifs for each genre

– Jefferson Bruchado
Nov 24 '18 at 23:03












3 Answers
3






active

oldest

votes


















2














Just use a dictionary:



genres_dict = {k:  for k in ('fight', 'win', 'knowledge', 'biography')}

for genre in genres:
write_jsonl(genres_dict[genre], genre, rating, title, genre)


A variable number of variable is not the recommended approach.



Related: How do I create a variable number of variables?.






share|improve this answer































    2














    You could find your variables in locals()/globals() like so



    for genre in genres:
    #.... Ommited ////// Here is where I call the function
    write_jsonl(locals()[genre + '_movies'], genre, rating, title, genre) #here is the call of the function





    share|improve this answer































      2














      As suggested by most use a dictionary, and then if you want and I think what you are intending for it to do is to then store the dictionary in a list. However, your code shows a problem where you passed a string for what I believe you intend to be a list.



      def write_jsonl(movie_list, genre, rating, title, json_name):
      d= {'title': title, 'genre': genre, 'rating': rating}
      movie_list.append(d) #<-- movie_list based on your traceback is a str
      # print(action_movies)
      with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
      writer.write(movie_list)


      The example below works as intended:



      all_movie_list = 

      def write_jsonl(movie_list, genre, rating, title, json_name):
      d= {'title': title, 'genre': genre, 'rating': rating}
      movie_list.append(d)
      # print(action_movies)
      with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
      writer.write(movie_list)

      write_jsonl(all_movie_list,'Crime','10','Godfather','test')

      all_movie_list
      [{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


      The better way is to store your list of titles by genre in a dictionary, you can use the defaultdict data model from the Python standard library for that.



      from collections import defaultdict
      movie_list = defaultdict(list)

      def write_jsonl(movie_list, genre, rating, title, json_name):
      d= {'title': title, 'genre': genre, 'rating': rating}
      movie_list['{}_movies'.format(genre)].append(d)
      # print(action_movies)
      with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
      writer.write(movie_list)

      movie_list
      >>defaultdict(list,
      {'Crime_movies': [{'title': 'Godfather',
      'genre': 'Crime',
      'rating': '10'}]})

      movie_list['Crime_movies']
      >>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


      Also do not use inbuilt method or reserved names as variables, I replaced your dict variable to just d.






      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%2f53463077%2fdinamically-var-in-parameter-of-a-function%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        Just use a dictionary:



        genres_dict = {k:  for k in ('fight', 'win', 'knowledge', 'biography')}

        for genre in genres:
        write_jsonl(genres_dict[genre], genre, rating, title, genre)


        A variable number of variable is not the recommended approach.



        Related: How do I create a variable number of variables?.






        share|improve this answer




























          2














          Just use a dictionary:



          genres_dict = {k:  for k in ('fight', 'win', 'knowledge', 'biography')}

          for genre in genres:
          write_jsonl(genres_dict[genre], genre, rating, title, genre)


          A variable number of variable is not the recommended approach.



          Related: How do I create a variable number of variables?.






          share|improve this answer


























            2












            2








            2







            Just use a dictionary:



            genres_dict = {k:  for k in ('fight', 'win', 'knowledge', 'biography')}

            for genre in genres:
            write_jsonl(genres_dict[genre], genre, rating, title, genre)


            A variable number of variable is not the recommended approach.



            Related: How do I create a variable number of variables?.






            share|improve this answer













            Just use a dictionary:



            genres_dict = {k:  for k in ('fight', 'win', 'knowledge', 'biography')}

            for genre in genres:
            write_jsonl(genres_dict[genre], genre, rating, title, genre)


            A variable number of variable is not the recommended approach.



            Related: How do I create a variable number of variables?.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 24 '18 at 23:23









            jppjpp

            101k2164114




            101k2164114

























                2














                You could find your variables in locals()/globals() like so



                for genre in genres:
                #.... Ommited ////// Here is where I call the function
                write_jsonl(locals()[genre + '_movies'], genre, rating, title, genre) #here is the call of the function





                share|improve this answer




























                  2














                  You could find your variables in locals()/globals() like so



                  for genre in genres:
                  #.... Ommited ////// Here is where I call the function
                  write_jsonl(locals()[genre + '_movies'], genre, rating, title, genre) #here is the call of the function





                  share|improve this answer


























                    2












                    2








                    2







                    You could find your variables in locals()/globals() like so



                    for genre in genres:
                    #.... Ommited ////// Here is where I call the function
                    write_jsonl(locals()[genre + '_movies'], genre, rating, title, genre) #here is the call of the function





                    share|improve this answer













                    You could find your variables in locals()/globals() like so



                    for genre in genres:
                    #.... Ommited ////// Here is where I call the function
                    write_jsonl(locals()[genre + '_movies'], genre, rating, title, genre) #here is the call of the function






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 24 '18 at 23:05









                    Filip MłynarskiFilip Młynarski

                    1,7961413




                    1,7961413























                        2














                        As suggested by most use a dictionary, and then if you want and I think what you are intending for it to do is to then store the dictionary in a list. However, your code shows a problem where you passed a string for what I believe you intend to be a list.



                        def write_jsonl(movie_list, genre, rating, title, json_name):
                        d= {'title': title, 'genre': genre, 'rating': rating}
                        movie_list.append(d) #<-- movie_list based on your traceback is a str
                        # print(action_movies)
                        with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                        writer.write(movie_list)


                        The example below works as intended:



                        all_movie_list = 

                        def write_jsonl(movie_list, genre, rating, title, json_name):
                        d= {'title': title, 'genre': genre, 'rating': rating}
                        movie_list.append(d)
                        # print(action_movies)
                        with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                        writer.write(movie_list)

                        write_jsonl(all_movie_list,'Crime','10','Godfather','test')

                        all_movie_list
                        [{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                        The better way is to store your list of titles by genre in a dictionary, you can use the defaultdict data model from the Python standard library for that.



                        from collections import defaultdict
                        movie_list = defaultdict(list)

                        def write_jsonl(movie_list, genre, rating, title, json_name):
                        d= {'title': title, 'genre': genre, 'rating': rating}
                        movie_list['{}_movies'.format(genre)].append(d)
                        # print(action_movies)
                        with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                        writer.write(movie_list)

                        movie_list
                        >>defaultdict(list,
                        {'Crime_movies': [{'title': 'Godfather',
                        'genre': 'Crime',
                        'rating': '10'}]})

                        movie_list['Crime_movies']
                        >>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                        Also do not use inbuilt method or reserved names as variables, I replaced your dict variable to just d.






                        share|improve this answer






























                          2














                          As suggested by most use a dictionary, and then if you want and I think what you are intending for it to do is to then store the dictionary in a list. However, your code shows a problem where you passed a string for what I believe you intend to be a list.



                          def write_jsonl(movie_list, genre, rating, title, json_name):
                          d= {'title': title, 'genre': genre, 'rating': rating}
                          movie_list.append(d) #<-- movie_list based on your traceback is a str
                          # print(action_movies)
                          with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                          writer.write(movie_list)


                          The example below works as intended:



                          all_movie_list = 

                          def write_jsonl(movie_list, genre, rating, title, json_name):
                          d= {'title': title, 'genre': genre, 'rating': rating}
                          movie_list.append(d)
                          # print(action_movies)
                          with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                          writer.write(movie_list)

                          write_jsonl(all_movie_list,'Crime','10','Godfather','test')

                          all_movie_list
                          [{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                          The better way is to store your list of titles by genre in a dictionary, you can use the defaultdict data model from the Python standard library for that.



                          from collections import defaultdict
                          movie_list = defaultdict(list)

                          def write_jsonl(movie_list, genre, rating, title, json_name):
                          d= {'title': title, 'genre': genre, 'rating': rating}
                          movie_list['{}_movies'.format(genre)].append(d)
                          # print(action_movies)
                          with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                          writer.write(movie_list)

                          movie_list
                          >>defaultdict(list,
                          {'Crime_movies': [{'title': 'Godfather',
                          'genre': 'Crime',
                          'rating': '10'}]})

                          movie_list['Crime_movies']
                          >>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                          Also do not use inbuilt method or reserved names as variables, I replaced your dict variable to just d.






                          share|improve this answer




























                            2












                            2








                            2







                            As suggested by most use a dictionary, and then if you want and I think what you are intending for it to do is to then store the dictionary in a list. However, your code shows a problem where you passed a string for what I believe you intend to be a list.



                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list.append(d) #<-- movie_list based on your traceback is a str
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)


                            The example below works as intended:



                            all_movie_list = 

                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list.append(d)
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)

                            write_jsonl(all_movie_list,'Crime','10','Godfather','test')

                            all_movie_list
                            [{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                            The better way is to store your list of titles by genre in a dictionary, you can use the defaultdict data model from the Python standard library for that.



                            from collections import defaultdict
                            movie_list = defaultdict(list)

                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list['{}_movies'.format(genre)].append(d)
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)

                            movie_list
                            >>defaultdict(list,
                            {'Crime_movies': [{'title': 'Godfather',
                            'genre': 'Crime',
                            'rating': '10'}]})

                            movie_list['Crime_movies']
                            >>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                            Also do not use inbuilt method or reserved names as variables, I replaced your dict variable to just d.






                            share|improve this answer















                            As suggested by most use a dictionary, and then if you want and I think what you are intending for it to do is to then store the dictionary in a list. However, your code shows a problem where you passed a string for what I believe you intend to be a list.



                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list.append(d) #<-- movie_list based on your traceback is a str
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)


                            The example below works as intended:



                            all_movie_list = 

                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list.append(d)
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)

                            write_jsonl(all_movie_list,'Crime','10','Godfather','test')

                            all_movie_list
                            [{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                            The better way is to store your list of titles by genre in a dictionary, you can use the defaultdict data model from the Python standard library for that.



                            from collections import defaultdict
                            movie_list = defaultdict(list)

                            def write_jsonl(movie_list, genre, rating, title, json_name):
                            d= {'title': title, 'genre': genre, 'rating': rating}
                            movie_list['{}_movies'.format(genre)].append(d)
                            # print(action_movies)
                            with jsonlines.open(json_name+'.jsonl', mode='w') as writer:
                            writer.write(movie_list)

                            movie_list
                            >>defaultdict(list,
                            {'Crime_movies': [{'title': 'Godfather',
                            'genre': 'Crime',
                            'rating': '10'}]})

                            movie_list['Crime_movies']
                            >>[{'title': 'Godfather', 'genre': 'Crime', 'rating': '10'}]


                            Also do not use inbuilt method or reserved names as variables, I replaced your dict variable to just d.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 24 '18 at 23:31

























                            answered Nov 24 '18 at 23:10









                            BernardLBernardL

                            2,38611130




                            2,38611130






























                                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%2f53463077%2fdinamically-var-in-parameter-of-a-function%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

                                Ottavio Pratesi

                                Tricia Helfer

                                15 giugno