[Tutor] creating new dictionary based on membership testing
Kent Johnson
kent37 at tds.net
Mon Mar 9 16:58:46 CET 2009
On Mon, Mar 9, 2009 at 10:28 AM, ski <norman at khine.net> 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 doesn't take advantage of dict lookup and it doesn't do exactly
what you asked; it will exclude dicts having any False value, not just
for is_selected. Better would be
d2 = []
for x in d1:
if x['is_selected'] != False:
d2.append(x)
This can be further simplified; you probably can just test
x['is_selected'] without comparing to False, and you can use a list
comprehension to simplify the structure:
d2 = [ x for x in d1 if x['is_selected'] ]
Kent
More information about the Tutor
mailing list