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 MRE (Minimal Reproducible Example).
Contents of the dicts are irrelevant:
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: ', ???
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?
Objects don't have names in Python, a name is an identifier that can be assigned to an object, and multiple names could be assigned to the same one.
However, an object-oriented way to do what you want would be to subclass the built-in dict
dictionary class and add a name
property 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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With