Is there a universal way of iterating over a set or values of a dict in Python 2.7?
Question: I expect the collection to be either a set or a dict. Problem is that:

    
    
    for element in collection:
        print element
    

will give me the elements if collection is a set, but indexes if collection is
a dict. What I want is a one-liner that will iterate over dict values.

Is that possible?


Answer: The most foolproof way to test for a mapping is to use `isinstance` on
[`collections.Mapping`](http://docs.python.org/library/collections.html#collections.Mapping):

    
    
    import collections
    
    for element in (collection.values() 
                    if isinstance(collection, collections.Mapping) else collection):
    

If you need to do that frequently (you shouldn't, or you probably have a
design issue), you could move it into a function:

    
    
    def values(collection):
        return (collection.values() 
                      if isinstance(collection, collections.Mapping) else collection)
    
    for element in values(collection):
    

