Dictionary 如何在python中从用户输入的名称创建字典?

Dictionary 如何在python中从用户输入的名称创建字典?,dictionary,Dictionary,假设用户输入hello 我想创建一个空字典hello={},它将在以后根据需要使用。如果您想创建一个由用户输入名称的字典,可以使用如下方法: while True: dictName = raw_input('Name: ') # use input on Python 3 if not dictName: break globals()[dictName] = {} print test1 print test2 上面的代码将要求输入一个名称,并将

假设用户输入
hello


我想创建一个空字典
hello={}
,它将在以后根据需要使用。

如果您想创建一个由用户输入名称的字典,可以使用如下方法:

while True:
    dictName = raw_input('Name: ') # use input on Python 3
    if not dictName:
        break

    globals()[dictName] = {}

print test1
print test2
上面的代码将要求输入一个名称,并将一个新的dict插入到
globals
,因此您可以稍后在代码中引用它(即打印它)

用法示例:

Name: test1
Name: test2
Name:
{}
{}

你是说你想让字典名为hello,还是想把用户的输入(在本例中是hello)添加到字典中?可能是'exec(“input={}”),其中输入是“hello”(未尝试)。我想让字典名为hello为什么我在这个问题上得到了-3?