获取词典名称

2024-06-30 15:55:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现自己需要遍历一个字典列表,而且每次迭代都需要我正在迭代的字典的名称。

这是一个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: ', ???

如果我只使用dc其中???,它将打印字典的全部内容。我怎样才能知道正在使用的词典的名字?


Tags: in名称列表for字典dcdictcommand
3条回答

对象在Python中没有名称,可以为同一对象指定多个名称。

然而,一种面向对象的方法是对内置的dict字典类进行子类化并向其添加name属性。它的实例的行为与普通词典完全一样,几乎可以在任何正常词典可以使用的地方使用。

class NamedDict(dict):
    def __init__(self, *args, **kwargs):
        try:
            self._name = kwargs.pop('name')
        except KeyError:
            raise KeyError('a "name" keyword argument must be supplied')
        super(NamedDict, self).__init__(*args, **kwargs)

    @classmethod
    def fromkeys(cls, name, seq, value=None):
        return cls(dict.fromkeys(seq, value), name=name)

    @property
    def name(self):
        return self._name

dict_list = [NamedDict.fromkeys('dict1', range(1,4)),
             NamedDict.fromkeys('dicta', range(1,4), 'a'),
             NamedDict.fromkeys('dict666', range(1,4), 666)]

for dc in dict_list:
    print 'the name of the dictionary is ', dc.name
    print 'the dictionary looks like ', dc

输出:

the name of the dictionary is  dict1
the dictionary looks like  {1: None, 2: None, 3: None}
the name of the dictionary is  dicta
the dictionary looks like  {1: 'a', 2: 'a', 3: 'a'}
the name of the dictionary is  dict666
the dictionary looks like  {1: 666, 2: 666, 3: 666}

不要使用dict_list,如果需要他们的名字,请使用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_

或者做一个dict_set并在locals()上迭代,但这比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

再一次:比罪还丑,但它确实有效。

您还应该考虑在每个字典中添加一个“name”键。

名字应该是:

for dc in dict_list:
    # Insert command that should replace ???
    print 'The name of the dictionary is: ', dc['name']

相关问题 更多 >