获取字典的名称

Gab*_*iel 8 python dictionary

我发现自己需要迭代一个由字典组成的列表,我需要,每次迭代,我正在迭代的字典的名称.

这是一个MWE(这个例子的内容与这个例子无关):

dict1 = {...}
dicta = {...}
dict666 = {...}

dict_list = [dict1, dicta, dict666]

for dc in dict_list:
    # Insert command that should replace ???
    print 'The name of the dictionary is: ', ???
Run Code Online (Sandbox Code Playgroud)

如果我只是dc在哪里使用???,它将打印字典的全部内容.如何获取正在使用的字典的名称?

Ada*_*ith 13

如果你需要他们的名字dict_list,请不要使用a ,使用a dict_dict.但实际上,你真的不应该这样做.不要在变量名中嵌入有意义的信息.得到它很难.

dict_dict = {'dict1':dict1, 'dicta':dicta, 'dict666':dict666}

for name,dict_ in dict_dict.items():
    print 'the name of the dictionary is ', name
    print 'the dictionary looks like ', dict_
Run Code Online (Sandbox Code Playgroud)

或者做一个dict_set迭代,locals()但这比罪恶更丑.

dict_set = {dict1,dicta,dict666}

for name,value in locals().items():
    if value in dict_set:
        print 'the name of the dictionary is ', name
        print 'the dictionary looks like ', value
Run Code Online (Sandbox Code Playgroud)

再说一次:比罪恶更丑,但它确实有效.

  • @Gabriel对程序实际有意义的任何信息都应存储在可变数据中,而不是变量名中. (4认同)
  • @Gabriel如果名称有意义,它应该在dict中,你可以访问它.否则将它视为一个比内存位置更容易记忆的一次性(它实际上只是一个指向"0xFAC4928FD9"的指针) (3认同)