Rob Rob - 1 year ago 82
Python Question

iterate over only two keys of python dictionary

What is the pythonic way to iterate over a dictionary with a setup like this:

dict = {'a': [1, 2, 3], 'b': [3, 4, 5], 'c': 6}

if I only wanted to iterate a for loop over all the values in
and skip
. There's obviously a million ways to solve this but I'd prefer to avoid something like:

for each in dict['a']:
# do something
for each in dict['b']:
# do something

of something destructive like:

del dict['c']
for k,v in dict.iteritems():

Answer Source

The more generic way is using filter-like approaches by putting an if in the end of a generator expression.

If you want to iterate over every iterable value, filter with hasattr:

for key in (k for k in dict if hasattr(dict[k], '__iter__')):
    for item in dict[key]:

If you want to exclude some keys, use a "not in" filter:

invalid = set(['c', 'd'])
for key in (k for k in dict if key not in invalid):

If you want to select only specific keys, use a "in" filter:

valid = set(['a', 'b'])
for key in (k for k in dict if key in valid):
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download