[Tutor] List of dictionaries membership test

Alan Gauld alan.gauld at btinternet.com
Fri Jan 2 17:58:55 CET 2009


"Norman Khine" <norman at khine.net> wrote

> >>> currencies = [{'sign': '\xe2\x82\xac', 'id': 'EUR', 
> >>> 'is_selected':
> False, 'title': 'EURO'}, {'sign': '\xc2\xa3', 'id': 'GBP', 
> 'is_selected': True, 'title': 'Pound'}, {'sign': '$', 'id': 'USD', 
> 'is_selected': False, 'title': 'Dollar'}]
>
> What is the simplest way to extract the dictionary that has key 
> 'is_selected'== True?

I'd use a list comprehension:

selected = [d for d in currencies if d['is_selected'] == True]

HTH


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list