Get name of dictionary

后端 未结 6 1722
感情败类
感情败类 2021-02-13 22:19

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.

Here\'s an MWE (the co

6条回答
  •  说谎
    说谎 (楼主)
    2021-02-13 22:53

    Objects don't have names in Python and multiple names could be assigned to the same object.

    However, an object-oriented way to do what you want would be to subclass the built-indictdictionary class and add anameproperty to it. Instances of it would behave exactly like normal dictionaries and could be used virtually anywhere a normal one could be.

    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
    

    Output:

    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}
    

提交回复
热议问题