[Tutor] List of dictionaries membership test

Kent Johnson kent37 at tds.net
Fri Jan 2 14:42:12 CET 2009


On Fri, Jan 2, 2009 at 8:17 AM, Norman Khine <norman at khine.net> wrote:
> Hello,
> I have this list
>
>>>> 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?

A list comprehension can extract a list of all dicts with the desired key:
In [2]: [ currency for currency in currencies if currency['is_selected'] ]
Out[2]: [{'id': 'GBP', 'is_selected': True, 'sign': '\xc2\xa3',
'title': 'Pound'}]

A generator expression lets you pick out just the first one without
iterating the whole list. This will raise StopIteration if there is no
selected item:
In [3]: ( currency for currency in currencies if
currency['is_selected'] ).next()
Out[3]: {'id': 'GBP', 'is_selected': True, 'sign': '\xc2\xa3', 'title': 'Pound'}


Of course a for loop works. You can use the else clause to handle the
case of no selection:
for currency in currencies:
  if currency['is_selected']:
    # Do something with currency
    print currency
    break
else: # this matches the indentation of 'for', it is not an 'elif'
  # Handle 'not found' case
  print 'No currency selected'

Kent


More information about the Tutor mailing list