Is there a general way to get an iterator that always iterates over values ββ(preferably, although it can also iterate keys) either in dictionaries or in other iterations (lists, sets ...)?
Let me clarify: when you execute " iter(list)", you get an iterator over the values ββ(not indexes that are very similar to the "key" in the dictionary), but when you do " iter(dict)", you get the keys.
Is there an instruction, attribute ... anything ... that always iterates over the values ββ(or keys) of the iteration, no matter what type of iterable it is?
I have code with the "append" method that should accept several different types of iterable types, and the only solution I could come up with is something like this:
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
I donβt know ... It looks a little ... awkward for me
It would be great to get a generic iterator for such cases, so that I can write something like ...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(element)
... if the iterator always returned values, or ...
def addThings(self, thingsToAdd):
for element in iter(thingsToAdd):
self._myListOfStuff.append(thingsToAdd[element])
... if the iterator returned the keys (I know that the concept of a key in a set is "special", so I would rather iterate over the values, but still ... maybe it could return a hash of the stored value).
Is there such a thing in Python? (By the way, I have to use Python2.4)
Thanks to everyone in advance.