[Tutor] creating new dictionary based on membership testing

A.T.Hofkamp a.t.hofkamp at tue.nl
Mon Mar 9 16:47:49 CET 2009


ski wrote:
> hello,
> 
> i have this list which contains a number of dictionaries.
> 
>  >>>d1 = [{'is_selected': False, 'id': 'AAC', 'title': 'Association of 
> Airline Cons.'}, {'is_selected': False, 'id': 'AALA', 'title': 'Adv. 
> Activity Licence. Auth.'}, {'is_selected': False, 'id': 'ABPCO', 
> 'title': 'Association of British Prof. Conf. Organisation'}, 
> {'is_selected': True, 'id': 'ABTA', 'title': 'Association of British 
> Travel Agents'}, {'is_selected': False, 'id': 'ABTOT', 'title': 
> 'Association of Bonded Travel Organisation Trust'}, {'is_selected': 
> False, 'id': 'AERA', 'title': 'Association of Europe Rail Agents'}]
> 
> what would be the correct way to create a new list with the dictionaries 
> but only for dictionaries with key
> 
> 'is_selected': False
> 
> here is what I have tried, so far, perhaps there is a better and less 
> error prone method:
> 
>  >>> d2 = []
>  >>> for x in d1:
> ...     if False in x.values():
> ...             d2.append(x)

This code is wrong, x.values() gives a list of values in the dictionary x, and 
if 'False' is in it, you append the dict. You never check for the key.

Thus

d1 = [ {'id':False} ]

would also be copied.


Also, if you have a dict, and you know which key to use, use that key!!
Key-lookup in a dict is very much faster than a linear search in a list like 
x.values().

You can do something like
[d for d in d1 if d['is_selected'] == False]
to get your dicts.

If 'is_selected' is not always present, it gets a bit more complicated, I'll 
leave that as an exercise for the interested reader :)


Sincerely,
Albert



More information about the Tutor mailing list