Is there a generic way of getting an iterator that always iterates over the values (preferably, although it may work iterating the keys too) of either dictionaries or other iterables (lists, sets…)?
Let me elaborate: When you execute “iter(list)” you get an iterator over the values (not the indexes, which sound pretty similar to the “key” in the dictionary) but when you do “iter(dict)” you get the keys.
Is there an instruction, attribute… whatever… which always iterates over the values (or the keys) of an iterable, no matter what type of iterable it is?
I have a code with an “append” method that needs to accept several different types of iterable types, and the only solution I’ve been able to come up with is something like this:
#!/usr/bin/python2.4
class Sample(object):
def __init__(self):
self._myListOfStuff = list()
def addThings(self, thingsToAdd):
myIterator = None
if (isinstance(thingsToAdd, list) or
isinstance(thingsToAdd, set) or
isinstance(thingsToAdd, tuple)):
myIterator = iter(thingsToAdd)
elif isinstance(thingsToAdd, dict):
myIterator = thingsToAdd.itervalues()
if myIterator:
for element in myIterator:
self._myListOfStuff.append(element)
if __name__ == '__main__':
sample = Sample()
myList = list([1,2])
mySet = set([3,4])
myTuple = tuple([5,6])
myDict = dict(
a= 7,
b= 8
)
sample.addThings(myList)
sample.addThings(mySet)
sample.addThings(myTuple)
sample.addThings(myDict)
print sample._myListOfStuff
#Outputs [1, 2, 3, 4, 5, 6, 7, 8]
I don’t know… It looks a little bit… clunky to me
It would be great to be able to get a common iterator for cases like this, so I could write something like…
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(element)
… if the iterator always gave the values, or…
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(thingsToAdd[element])
… if the iterator returned the keys (I know the concept of key in a set is kind of “special”, that’s why I would prefer iterating over the values but still… maybe it could return the hash of the stored value).
Is there such thing in Python? (I have to use Python2.4, by the way)
Thank you all in advance
Most collections have no concept or “keys” or “values”. They just store items, and iterating over them gives you those items. Only mappings (dict-likes) provide “keys” and “values”. And the default way of iterating them uses the keys because
for x in collection: assert x in collectionshould be an invariant (and a(key, value) in drarely makes sense, as opposed tokey in d). So there is no method to iterate over the values only, because the least collections have things called “values”.You can, however, choose to ignore the keys in mappings. Since you have to use Python 2.4, using ABCs is out of questions… I fear the simplest way would be:
Which can still break, but handles dicts and similar mappings.