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