How can I rename a dictionary within a program?How do I create a variable number of variables?How to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How do I check whether a file exists without exceptions?What is the best way to iterate over a dictionary?How can I safely create a nested directory?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryIterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?

Having to constantly redo everything because I don't know how to do it?

あまり気持ちのいいものではない in this context

Origin of the convolution theorem

A quine of sorts

Fully submerged water bath for stove top baking?

Active wildlife outside the window- Good or Bad for Cat psychology?

What prevents a US state from colonizing a smaller state?

List manipulation: conditional result based on variable-length sublists

How to describe POV characters?

Cooking a nice pan seared steak for picky eaters

Bin Packing with Relational Penalization

How does mmorpg store data?

80's-90's TV show or movie about life clocks

Why did the Apple //e make a hideous noise if you inserted the disk upside down?

How can I deal with extreme temperatures in a hotel room?

Is it okay to submit a paper from a master's thesis without informing the advisor?

Can dual citizens open crypto exchange accounts where U.S. citizens are prohibited?

Robots in a spaceship

What was the point of separating stdout and stderr?

"I am [the / an] owner of a bookstore"?

Do home values typically rise and fall consistently across different price ranges?

Why was Pan Am Flight 103 flying over Lockerbie?

Iterate over deepest values in a nested Association

What happens if a caster is surprised while casting a spell with a long casting time?



How can I rename a dictionary within a program?


How do I create a variable number of variables?How to merge two dictionaries in a single expression?How do I sort a list of dictionaries by a value of the dictionary?How do I check whether a file exists without exceptions?What is the best way to iterate over a dictionary?How can I safely create a nested directory?How do I sort a dictionary by value?Add new keys to a dictionary?Check if a given key already exists in a dictionaryIterating over dictionaries using 'for' loopsHow to remove a key from a Python dictionary?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I ask the user of my program to input the number of datasets he/she wants to investigate, e.g. three datasets. Accordingly, I should then create three dictionaries (dataset_1, dataset_2, and dataset_3) to hold the values for the various parameters. Since I do not know beforehand the number of datasets the user wants to investigate, I have to create and name the dictionaries within the program.



Apparently, Python does not let me do that. I could not rename the dictionary once it has been created.



I have tried using os.rename("oldname", "newname"), but that only works if I have a file stored on my computer hard disk. I could not get it to work with an object that lives only within my program.



number_sets = input('Input the number of datasets to investigate:')

for dataset in range(number_sets):
init_dict =
# create dictionary name for the particular dataset
dict_name = ''.join(['dataset_', str(dataset+1)])
# change the dictionary´s name
# HOW CAN I CHANGE THE DICTIONARY´S NAME FROM "INIT_DICT"
# TO "DATASET_1", WHICH IS THE STRING RESULT FOR DICT_NAME?


I would like to have in the end



dataset_1 =
dataset_2 =



and so on.










share|improve this question

















  • 2





    Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

    – Kevin
    Mar 25 at 15:15












  • You may need to copy them and assign them a new name.

    – eddwinpaz
    Mar 25 at 15:16

















1















I ask the user of my program to input the number of datasets he/she wants to investigate, e.g. three datasets. Accordingly, I should then create three dictionaries (dataset_1, dataset_2, and dataset_3) to hold the values for the various parameters. Since I do not know beforehand the number of datasets the user wants to investigate, I have to create and name the dictionaries within the program.



Apparently, Python does not let me do that. I could not rename the dictionary once it has been created.



I have tried using os.rename("oldname", "newname"), but that only works if I have a file stored on my computer hard disk. I could not get it to work with an object that lives only within my program.



number_sets = input('Input the number of datasets to investigate:')

for dataset in range(number_sets):
init_dict =
# create dictionary name for the particular dataset
dict_name = ''.join(['dataset_', str(dataset+1)])
# change the dictionary´s name
# HOW CAN I CHANGE THE DICTIONARY´S NAME FROM "INIT_DICT"
# TO "DATASET_1", WHICH IS THE STRING RESULT FOR DICT_NAME?


I would like to have in the end



dataset_1 =
dataset_2 =



and so on.










share|improve this question

















  • 2





    Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

    – Kevin
    Mar 25 at 15:15












  • You may need to copy them and assign them a new name.

    – eddwinpaz
    Mar 25 at 15:16













1












1








1








I ask the user of my program to input the number of datasets he/she wants to investigate, e.g. three datasets. Accordingly, I should then create three dictionaries (dataset_1, dataset_2, and dataset_3) to hold the values for the various parameters. Since I do not know beforehand the number of datasets the user wants to investigate, I have to create and name the dictionaries within the program.



Apparently, Python does not let me do that. I could not rename the dictionary once it has been created.



I have tried using os.rename("oldname", "newname"), but that only works if I have a file stored on my computer hard disk. I could not get it to work with an object that lives only within my program.



number_sets = input('Input the number of datasets to investigate:')

for dataset in range(number_sets):
init_dict =
# create dictionary name for the particular dataset
dict_name = ''.join(['dataset_', str(dataset+1)])
# change the dictionary´s name
# HOW CAN I CHANGE THE DICTIONARY´S NAME FROM "INIT_DICT"
# TO "DATASET_1", WHICH IS THE STRING RESULT FOR DICT_NAME?


I would like to have in the end



dataset_1 =
dataset_2 =



and so on.










share|improve this question














I ask the user of my program to input the number of datasets he/she wants to investigate, e.g. three datasets. Accordingly, I should then create three dictionaries (dataset_1, dataset_2, and dataset_3) to hold the values for the various parameters. Since I do not know beforehand the number of datasets the user wants to investigate, I have to create and name the dictionaries within the program.



Apparently, Python does not let me do that. I could not rename the dictionary once it has been created.



I have tried using os.rename("oldname", "newname"), but that only works if I have a file stored on my computer hard disk. I could not get it to work with an object that lives only within my program.



number_sets = input('Input the number of datasets to investigate:')

for dataset in range(number_sets):
init_dict =
# create dictionary name for the particular dataset
dict_name = ''.join(['dataset_', str(dataset+1)])
# change the dictionary´s name
# HOW CAN I CHANGE THE DICTIONARY´S NAME FROM "INIT_DICT"
# TO "DATASET_1", WHICH IS THE STRING RESULT FOR DICT_NAME?


I would like to have in the end



dataset_1 =
dataset_2 =



and so on.







python dictionary






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 25 at 15:14









CarvalhoCarvalho

62 bronze badges




62 bronze badges







  • 2





    Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

    – Kevin
    Mar 25 at 15:15












  • You may need to copy them and assign them a new name.

    – eddwinpaz
    Mar 25 at 15:16












  • 2





    Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

    – Kevin
    Mar 25 at 15:15












  • You may need to copy them and assign them a new name.

    – eddwinpaz
    Mar 25 at 15:16







2




2





Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

– Kevin
Mar 25 at 15:15






Rule of thumb: if you're trying to create a bunch of variables with names that are all identical except they end with different numbers, you should be using a list instead. datasets = [] outside the loop, and datasets.append(init_dict) inside the loop. Then you can get the third dataset with datasets[2].

– Kevin
Mar 25 at 15:15














You may need to copy them and assign them a new name.

– eddwinpaz
Mar 25 at 15:16





You may need to copy them and assign them a new name.

– eddwinpaz
Mar 25 at 15:16












4 Answers
4






active

oldest

votes


















2














You don't (need to). Keep a list of data sets.



datasets = []
for i in range(number_sets):
init_dict =
...
datasets.append(init_dict)


Then you have datasets[0], datasets[1], etc., rather than dataset_1, dataset_2, etc.



Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dicts added to datasets on previous iterations.






share|improve this answer
































    0














    If you want to create variables like that you could use the globals



    number_sets = 2
    for dataset in range(number_sets):
    dict_name = ''.join(['dataset_', str(dataset+1)])
    globals() [dict_name] =

    print(dataset_1)
    print(dataset_2)


    However this is not a good practice, and it should be avoided, if you need to keep several variables that are similar the best thing to do is to create a list.






    share|improve this answer






























      0














      You can use a single dict and then add all the data sets into it as a dictionary:



      all_datasets = 

      for i in range(number_sets):
      all_datasets['dataset'+str(i+1)] =


      And then you can access the data by using:



      all_datasets['dataset_1']





      share|improve this answer






























        0














        This question gets asked many times in many different variants (this is one of the more prominent ones, for example). The answer is always the same:



        It is not easily possible and most of the time not a good idea to create python variable names from strings.



        The more easy, approachable, safe and usable way is to just use another dictionary. One of the cool things about dictionaries: any object can become a key / value. So the possibilities are nearly endless. In your code, this can be done easily with a dict comprehension:



        number_sets = int(input('Input the number of datasets to investigate:')) # also notice that you have to add int() here
        data = ''.join(['dataset_', str(dataset + 1)]): for dataset in range(number_sets)
        print(data)

        >>> 5
        'dataset_1': , 'dataset_2': , 'dataset_3': , 'dataset_4': , 'dataset_5':


        Afterwards, these dictionaries can be easily accessed via data[name_of_dataset]. Thats how it should be done.






        share|improve this answer























        • Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

          – Carvalho
          Mar 25 at 17:41














        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%2f55340974%2fhow-can-i-rename-a-dictionary-within-a-program%23new-answer', 'question_page');

        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        2














        You don't (need to). Keep a list of data sets.



        datasets = []
        for i in range(number_sets):
        init_dict =
        ...
        datasets.append(init_dict)


        Then you have datasets[0], datasets[1], etc., rather than dataset_1, dataset_2, etc.



        Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dicts added to datasets on previous iterations.






        share|improve this answer





























          2














          You don't (need to). Keep a list of data sets.



          datasets = []
          for i in range(number_sets):
          init_dict =
          ...
          datasets.append(init_dict)


          Then you have datasets[0], datasets[1], etc., rather than dataset_1, dataset_2, etc.



          Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dicts added to datasets on previous iterations.






          share|improve this answer



























            2












            2








            2







            You don't (need to). Keep a list of data sets.



            datasets = []
            for i in range(number_sets):
            init_dict =
            ...
            datasets.append(init_dict)


            Then you have datasets[0], datasets[1], etc., rather than dataset_1, dataset_2, etc.



            Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dicts added to datasets on previous iterations.






            share|improve this answer















            You don't (need to). Keep a list of data sets.



            datasets = []
            for i in range(number_sets):
            init_dict =
            ...
            datasets.append(init_dict)


            Then you have datasets[0], datasets[1], etc., rather than dataset_1, dataset_2, etc.



            Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dicts added to datasets on previous iterations.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            answered Mar 25 at 15:20


























            community wiki





            chepner
























                0














                If you want to create variables like that you could use the globals



                number_sets = 2
                for dataset in range(number_sets):
                dict_name = ''.join(['dataset_', str(dataset+1)])
                globals() [dict_name] =

                print(dataset_1)
                print(dataset_2)


                However this is not a good practice, and it should be avoided, if you need to keep several variables that are similar the best thing to do is to create a list.






                share|improve this answer



























                  0














                  If you want to create variables like that you could use the globals



                  number_sets = 2
                  for dataset in range(number_sets):
                  dict_name = ''.join(['dataset_', str(dataset+1)])
                  globals() [dict_name] =

                  print(dataset_1)
                  print(dataset_2)


                  However this is not a good practice, and it should be avoided, if you need to keep several variables that are similar the best thing to do is to create a list.






                  share|improve this answer

























                    0












                    0








                    0







                    If you want to create variables like that you could use the globals



                    number_sets = 2
                    for dataset in range(number_sets):
                    dict_name = ''.join(['dataset_', str(dataset+1)])
                    globals() [dict_name] =

                    print(dataset_1)
                    print(dataset_2)


                    However this is not a good practice, and it should be avoided, if you need to keep several variables that are similar the best thing to do is to create a list.






                    share|improve this answer













                    If you want to create variables like that you could use the globals



                    number_sets = 2
                    for dataset in range(number_sets):
                    dict_name = ''.join(['dataset_', str(dataset+1)])
                    globals() [dict_name] =

                    print(dataset_1)
                    print(dataset_2)


                    However this is not a good practice, and it should be avoided, if you need to keep several variables that are similar the best thing to do is to create a list.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 25 at 15:23









                    MntfrMntfr

                    3072 silver badges14 bronze badges




                    3072 silver badges14 bronze badges





















                        0














                        You can use a single dict and then add all the data sets into it as a dictionary:



                        all_datasets = 

                        for i in range(number_sets):
                        all_datasets['dataset'+str(i+1)] =


                        And then you can access the data by using:



                        all_datasets['dataset_1']





                        share|improve this answer



























                          0














                          You can use a single dict and then add all the data sets into it as a dictionary:



                          all_datasets = 

                          for i in range(number_sets):
                          all_datasets['dataset'+str(i+1)] =


                          And then you can access the data by using:



                          all_datasets['dataset_1']





                          share|improve this answer

























                            0












                            0








                            0







                            You can use a single dict and then add all the data sets into it as a dictionary:



                            all_datasets = 

                            for i in range(number_sets):
                            all_datasets['dataset'+str(i+1)] =


                            And then you can access the data by using:



                            all_datasets['dataset_1']





                            share|improve this answer













                            You can use a single dict and then add all the data sets into it as a dictionary:



                            all_datasets = 

                            for i in range(number_sets):
                            all_datasets['dataset'+str(i+1)] =


                            And then you can access the data by using:



                            all_datasets['dataset_1']






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Mar 25 at 15:24









                            heena bawaheena bawa

                            7134 silver badges5 bronze badges




                            7134 silver badges5 bronze badges





















                                0














                                This question gets asked many times in many different variants (this is one of the more prominent ones, for example). The answer is always the same:



                                It is not easily possible and most of the time not a good idea to create python variable names from strings.



                                The more easy, approachable, safe and usable way is to just use another dictionary. One of the cool things about dictionaries: any object can become a key / value. So the possibilities are nearly endless. In your code, this can be done easily with a dict comprehension:



                                number_sets = int(input('Input the number of datasets to investigate:')) # also notice that you have to add int() here
                                data = ''.join(['dataset_', str(dataset + 1)]): for dataset in range(number_sets)
                                print(data)

                                >>> 5
                                'dataset_1': , 'dataset_2': , 'dataset_3': , 'dataset_4': , 'dataset_5':


                                Afterwards, these dictionaries can be easily accessed via data[name_of_dataset]. Thats how it should be done.






                                share|improve this answer























                                • Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                  – Carvalho
                                  Mar 25 at 17:41
















                                0














                                This question gets asked many times in many different variants (this is one of the more prominent ones, for example). The answer is always the same:



                                It is not easily possible and most of the time not a good idea to create python variable names from strings.



                                The more easy, approachable, safe and usable way is to just use another dictionary. One of the cool things about dictionaries: any object can become a key / value. So the possibilities are nearly endless. In your code, this can be done easily with a dict comprehension:



                                number_sets = int(input('Input the number of datasets to investigate:')) # also notice that you have to add int() here
                                data = ''.join(['dataset_', str(dataset + 1)]): for dataset in range(number_sets)
                                print(data)

                                >>> 5
                                'dataset_1': , 'dataset_2': , 'dataset_3': , 'dataset_4': , 'dataset_5':


                                Afterwards, these dictionaries can be easily accessed via data[name_of_dataset]. Thats how it should be done.






                                share|improve this answer























                                • Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                  – Carvalho
                                  Mar 25 at 17:41














                                0












                                0








                                0







                                This question gets asked many times in many different variants (this is one of the more prominent ones, for example). The answer is always the same:



                                It is not easily possible and most of the time not a good idea to create python variable names from strings.



                                The more easy, approachable, safe and usable way is to just use another dictionary. One of the cool things about dictionaries: any object can become a key / value. So the possibilities are nearly endless. In your code, this can be done easily with a dict comprehension:



                                number_sets = int(input('Input the number of datasets to investigate:')) # also notice that you have to add int() here
                                data = ''.join(['dataset_', str(dataset + 1)]): for dataset in range(number_sets)
                                print(data)

                                >>> 5
                                'dataset_1': , 'dataset_2': , 'dataset_3': , 'dataset_4': , 'dataset_5':


                                Afterwards, these dictionaries can be easily accessed via data[name_of_dataset]. Thats how it should be done.






                                share|improve this answer













                                This question gets asked many times in many different variants (this is one of the more prominent ones, for example). The answer is always the same:



                                It is not easily possible and most of the time not a good idea to create python variable names from strings.



                                The more easy, approachable, safe and usable way is to just use another dictionary. One of the cool things about dictionaries: any object can become a key / value. So the possibilities are nearly endless. In your code, this can be done easily with a dict comprehension:



                                number_sets = int(input('Input the number of datasets to investigate:')) # also notice that you have to add int() here
                                data = ''.join(['dataset_', str(dataset + 1)]): for dataset in range(number_sets)
                                print(data)

                                >>> 5
                                'dataset_1': , 'dataset_2': , 'dataset_3': , 'dataset_4': , 'dataset_5':


                                Afterwards, these dictionaries can be easily accessed via data[name_of_dataset]. Thats how it should be done.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 25 at 15:28









                                FlobFlob

                                7631 gold badge1 silver badge14 bronze badges




                                7631 gold badge1 silver badge14 bronze badges












                                • Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                  – Carvalho
                                  Mar 25 at 17:41


















                                • Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                  – Carvalho
                                  Mar 25 at 17:41

















                                Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                – Carvalho
                                Mar 25 at 17:41






                                Thanks everybody for answering and commenting on my questions. You have pointed out to me the way to go. I will go through all the answers carefully to figure out the best solution to my problem.

                                – Carvalho
                                Mar 25 at 17:41


















                                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%2f55340974%2fhow-can-i-rename-a-dictionary-within-a-program%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

                                Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                                SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                                은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현