我发现自己需要迭代一个由字典组成的列表,我需要,每次迭代,我正在迭代的字典的名称.
这是一个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)
再说一次:比罪恶更丑,但它确实有效.