filter()ing a dict

John Hunter jdhunter at ace.bsd.uchicago.edu
Thu Aug 7 17:41:05 CEST 2003


>>>>> "Robin" == Robin Cull <robin.cull at pace.co.uk> writes:

    Robin> My question is, does anybody else think that when calling
    Robin> filter(f, dict), it should return a dict of the keys and
    Robin> values of the former dict where the values satisfy the
    Robin> conditions defined by f()?

The problem is not with filter.  When you do

  d = {'k1':1, 'k2':2}
  for x in d: print x

It prints the keys.  That is: by default, iterating over a dictionary
iterates over the keys.  So when you filter a dict, it iterates over
the dictionary which means iterating over the keys.  SO filter and
dict are behaving as advertised.  As you noted, you can call
dictionary functions to iterate over the keys, values, or key, value
pairs. 

It is easy to do what you want with list comprehensions

myDict = {"key 1": ["value 1", "value 2", "value 3", "value 4"],
          "key 2": ["value 1", "value 2"],
          "key 3": ["value2", "value 3", "value 4"],
          "key 4": ["value 1", "value 2", "value 3", "value 4"]}


len4Dict = dict([ (k,v) for k,v in myDict.items() if len(v)==4])
print len4Dict


Cheers, 
John Hunter





More information about the Python-list mailing list