Dictionary Iteration Ways
First of all, there are several ways you can loop a dictionary.
The cycle directly above the dictionary:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> for key in z: ... print key, ... 'x' 'z'
Note that the loop variables that are returned when you simply iterate over the dictionary are the keys, not the values associated with these keys.
Quoting from dictionary values:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> for value in z.values():
Cycle and keys and values:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> for key, value in z.items(): # Again, iteritems() for memory-efficiency ... print key, value, ... 'x' (123,'SE',2,1) 'z' (124,'CI',1,1)
The last two are somewhat more efficient than looping through the keys and running z [key] to get the value. It is also possibly more readable.
Based on these ...
List of concepts
List of concepts . For a simple search case, only "CI":
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> [key for key, value in z.items() if 'CI' in value] ['z']
To search for dict keys containing multiple search items:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> search_items = ('CI', 1)
To search for dict keys containing any of several search items:
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> search_items = ('CI', 'SE', 'JP')
If the last two look too complex as single-line, you can rewrite the last bit as a separate function.
>>> z = {'x':(123,'SE',2,1),'z':(124,'CI',1,1)} >>> search_items = ('CI', 'SE', 'JP')
Once you get used to the syntax [x for x in iterable if condition (x)], the format should be very easy to read and follow.