简体   繁体   English

如何在程序中重命名词典?

[英]How can I rename a dictionary within a program?

I ask the user of my program to input the number of datasets he/she wants to investigate, eg three datasets. 我要求程序的用户输入他/她想调查的数据集的数量,例如三个数据集。 Accordingly, I should then create three dictionaries (dataset_1, dataset_2, and dataset_3) to hold the values for the various parameters. 因此,我应该创建三个字典(数据集_1,数据集_2和数据集_3)来保存各种参数的值。 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. 显然,Python不允许我这样做。 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. 我曾尝试使用os.rename(“ oldname”,“ newname”),但这仅在计算机硬盘上存储了文件的情况下有效。 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 = {} 数据集_1 = {}数据集_2 = {}

and so on. 等等。

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. 然后,您将获得datasets[0]datasets[1]等,而不是datasets[1] dataset_1datasets[1] dataset_2等。

Inside the loop, init_dict is set to a brand new empty directory at the top of each iteration, without affecting the dict s added to datasets on previous iterations. 在循环内部,将init_dict设置为每个迭代顶部的全新空目录,而不会影响先前迭代中添加到datasetsdict

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. 但是,这不是一个好习惯,因此,如果需要保留几个相似的变量,则最好避免创建列表。

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']

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. 从字符串创建python变量名称并非易事,而且在大多数情况下不是一个好主意。

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: 在您的代码中,可以通过dict理解轻松地完成此操作:

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] . 之后,可以通过data[name_of_dataset]轻松访问这些词典。 Thats how it should be done. 那就是应该怎么做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM