问题描述
我发现自己需要遍历由字典组成的列表,并且每次迭代都需要迭代所用词典的名称.
I find myself needing to iterate over a list made of dictionaries and I need, for every iteration, the name of which dictionary I'm iterating on.
这里是MWE(字典的内容与本例无关):
Here's an MWE (the contents of the dicts are irrelevant for this example) :
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: ', ???
如果我只使用dc
,其中???
是,它将打印字典的全部内容.如何获得正在使用的词典的名称?
If I just use dc
where ???
is, it will print the entire contents of the dictionary. How can I get the name of the dictionary being used?
推荐答案
不要使用dict_list
,如果需要它们的名称,请使用dict_dict
.但是,实际上,您实际上不应该这样做.不要在变量名中嵌入有意义的信息.很难得到.
Don't use a dict_list
, use a dict_dict
if you need their names. In reality, though, you should really NOT be doing this. Don't embed meaningful information in variable names. It's tough to get.
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_
或者制作一个dict_set
并遍历locals()
,但这比罪恶丑陋.
Alternatively make a dict_set
and iterate over locals()
but this is uglier than sin.
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
再次:比罪恶丑陋,但确实有效.
Again: uglier than sin, but it DOES work.
这篇关于获取字典名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!